Search code examples
cmemoryrealloccalloc

realloc a triple pointer


Hi I have a triple pointer that I want to realloc when my original array is filled up. For some reason, the way I'm using realloc gives me a seg fault. Anybody have a sense why?

double ***matrixn;
matrixn=(double***) calloc(1,sizeof(double **));
for(i=0;i<1;i++){
    matrixn[i]=(double**)calloc(3,sizeof(double*));
    for(j=0;j<3;j++){
        matrixn[i][j]=(double*)calloc(4,sizeof(double));
    }
}

max_size=1

This next part takes place inside of a loop:

max_size+=1;

matrixn=realloc(matrixn,max_size*sizeof(double**));
matrixn[max_size-1]=(double**)calloc(3,sizeof(double*));

for (i=0;i<3;i++){
matrixn[max_size-1]=(double*)calloc(4,sizeof(double));
}

Thanks


Solution

  • In the loop of your second code block, you forgot index i. It should instead look like

    matrixn[max_size-1][i]=(double*)calloc(4,sizeof(double));