6
When performing a dynamic allocation of a vector or matrix in C, the pointer for that allocation changes address when leaving the function, before it was pointing to the initial address of the allocated area and just after the end of the respective function it points to the address 1. As shown below, the pointer is passed as parameter by the function to perform the subsequent 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 check that the address has been changed and at the end I lose access to this vector, not being able to perform memory misalignment or data manipulation. Why does this happen? What is the solution?
The two solutions are actually quite functional, although the second is more complex because it takes into consideration multiple indirect, which many people do not understand well, so the first solution becomes more practical for a more general purpose. Grateful!
– Pedro Augusto