Kwantuum Kwantuum - 1 month ago 5
C Question

Confused about pointers and passing them as arguments

I'm trying to create an array of arbitrary size, and for some reason, this code here works:

int rand_tab(unsigned int n, int min, int max, int** dest){
if(!(*dest = malloc(sizeof(int)*n))) return 0;
return 1;
}


with the random number generation in main:

int* tab;
if(!(rand_tab(taille, min, max, &tab))) return -1;
for(i=0; i<taille; i++) tab[i] = random(min, max);


but this crashes(though it compiles just fine):

int rand_tab(unsigned int n, int min, int max, int** dest){
if(!(*dest = malloc(sizeof(int)*n))) return 0;
for(i=0; i<n; i++) *dest[i] = random(min, max);
return 1;
}


since I pass
&tab
to the function,
dest
now points to
tab
, meaning
*dest[i]
should be equivalent to writing
tab[i]
in main.

If I replace
*dest[i]
by
*(*dest+i)
it works though. What is happening here?

Answer

The problem is that the following expression

*dest[i] = random(min, max)

needs parentheses around *dest:

(*dest)[i] = random(min, max)

Since square brackets [] operator has higher precedence than dereference operator *, order needs to be forced with parentheses to match the one that you need. Otherwise, C interprets dest as an array of pointers, reads a value from dest+1 (undefined behavior) and tries to dereference it (undefined behavior again).

Comments