Pointers as parameters to functions in c

6

Hello people, I have a small problem. I am creating a function that receives as parameters a double pointer. This function receives the parameter and assigns it dynamic memory. Once the memory is assigned, I call another function that assigns values to that pointer. But when doing the assignment of values gives me segmentation error, I suspect that the problem is in the passage of the pointers as a parameter, because when I do everything in the main and not in functions does not present 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;
}
    
asked by Patricio 03.04.2017 в 03:00
source

2 answers

4

As I mentioned in this other question ...

void asignarMemoriaDinamica(double** A){
  A=malloc(dim*sizeof(double*));   
}

Changes in A are uniquely local. For the changes to be reflected outside the function you have to work with an additional indirection level (in this case a triple pointer):

void asignarMemoriaDinamica(double*** A){
  *A=malloc(dim*sizeof(double*));   
}

In the function cargarA you will not have that problem because you are not changing the address pointed to by A but you work directly on the memory addressed by A (which is not the same).

What is the name of this new function?

double **A = 0; // No hay que perder las buenas costumbres
asignarMemoriaDinamica(&A);
    
answered by 03.04.2017 / 11:05
source
0
int main() {

    double **A;
    asignarMemoriaDinamica(&A);
    cargarA(&A);     

    return 0;

}
    
answered by 03.04.2017 в 03:34