krm krm - 1 month ago 5
C Question

How to treat possible NULL pointers in a 2d dynamic array in a C program?

When allocating memory for a 2d dynamic array in C, can you treat the inner array (columns) with a function like the following example? Also, how can you print the NULL pointer message with the number of the NULL column pointer?

int main()
{

....

int ** x = calloc(N, sizeof(*x));

for(int i=0; i<N; i++){
x[i]=malloc(sizeof(int));

error(x);
}

....

exit(0)
}



void error(int *x){

if(x==NULL){
printf(“Error”);
}

Answer

Change your function to

void error(int *x, int idx)

and call

error(x, i);