When performing a dynamic allocation of a vector or matrix in C, the pointer referring to this allocation changes address when leaving the function, whereas before it was pointing to the initial address of the allocated area and soon after the end of the respective area it points to address 1. As shown below, the pointer is passed as a parameter by the function to perform further manipulation of the allocated data.
#include <stdio.h>
#include <stdlib.h>
void aloca(int *vetorInt, int tamanho);
int main (void) {
int *vetor;
aloca(vetor, 2);
printf("END. NA MAIN: %d", vetor);
}
void aloca(int *vetorInt, int tamanho) {
//Inicializa o ponteiro com NULL para nao ter problema
vetorInt = NULL;
//Aloca n espaços
vetorInt = (int *) malloc(tamanho * sizeof(int));
//Verifica se foi alocado e exibe o endereço para qual o ponteiro aponta
if (vetorInt != NULL) {
printf("*** VETOR ALOCADO.\nENDERECO NA FUNCAO: %d ***\n", vetorInt);
getchar();
} else {
printf("*** NAO ALOCADO ***\n");
getchar();
}
}
When I run the code, I verify that the address has changed and in the end I lose access to this vector, and can not perform memory deallocation or data manipulation. Why does it happen? What is the solution?