Hi folks, I have a little problem. I am creating a function that receives a double pointer as a parameter. That function receives the parameter and allocates dynamic memory to it. Once the memory is allocated, I call another function that assigns values to that pointer. But when doing the assignment of values I get a segmentation error, I suspect that the problem is in the passing of pointers as a parameter, because when I do everything in main
it and not in functions, it does not present a problem. I pass the codes, so someone can guide me.
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#define dim 100
void asignarMemoriaDinamica(double** A){
int i;
A=malloc(dim*sizeof(double*));
for(i=0;i<dim;i++){
A[i]=malloc(dim*sizeof(double));
}
}
void cargarA(double** A){
int i,j;
srand(time(NULL));
for(i=0;i<dim;i++){
for(j=0;j<dim;j++){
int test = rand()%200 -100;
A[i][j]=test; //al ejecutar esta linea da error
printf("%.2lf ",A[i][j]);
}
printf("%s","\n");
}
}
int main() {
double **A;
asignarMemoriaDinamica(A);
cargarA(A);
return 0;
}
As I already mentioned in this other question ...
The changes in
A
are only and exclusively local. In order for the changes to be reflected outside the function you have to work with an additional level of indirection (in this case a triple pointer):In the function
cargarA
you won't have that problem because you're not changing the address pointed to byA
, but you're working directly on the memory addressed byA
(which is not the same thing).What is this new function called?