Home > Net >  language C double pointer variable in function
language C double pointer variable in function

Time:12-28

In the main function, I just declare double pointer variables and assign 2 dimensional matrix as below.

int main(){
double **XNODE;
XNODE = (double**)calloc(2,sizeof(double*));
for(int i=0; i<2; i  ){
XNODE[i] = (double*)calloc(3,sizeof(double));
}
XNODE[0][0] = 1.0; XNODE[0][1] = -1.0; XNODE[0][2] = -122.0;
XNODE[1][0] = 2.0; XNODE[1][1] = 3.0; XNODE[1][2] = -4.0;

test(*XNODE);
return 0;

and then put the XNODE variable in the below "test" function

void test(double*XNODE)
{
for(int i=0; i<2; i  ){
for(int j=0; j<3; j  ){
printf("%e ", *(XNODE 3*i j));
}
}

My expectation is 1 -1 -122 2 3 -4

However the output is as below 1 -1 -122 1.63e-322 2 3

How can I fix this problem??

CodePudding user response:

test(*XNODE); passes the pointer saved in XNODE[0]. That pointer's value was from the allocation when (i==0) and XNODE[i] = (double*)calloc(3,sizeof(double));. That allocation has memory for 3 double.

test() attempts to print 6 adjacent double. The first 3 are as expected. The rest are outside the allocation and so undefined behavior (UB).

How can I fix this problem??

  • Rewrite test() to test(int rows, int cols, double **d).

  • Re-write test() body to use rows, cols, d.

  • Pass test(2, 3, XNODE).

CodePudding user response:

The code inside the function, *(XNODE 3*i j), expects to be able to calculate the location of any array element as an offset from the base pointer, XNODE. To do this, all of the array elements must be in memory consecutively after the start of the array.

The allocations in main do not do this. The loop allocates memory for each row separately, so each row is wherever the calloc routine puts it. They are unlikely to be consecutively in memory.

To allocate memory correctly, you must allocate all of the memory for the elements of the array in one allocation. Calculate that amount of memory, allocate it, and pass the pointer to that memory to test. You can do this with double *XNode = calloc(2 * 3 * sizeof *XNode);.

To access that memory, you can do it the same way the code in test does: The element in row i, column j is *(XNode 3*i j). This can also be written XNode[3*i j].

  • Related