简体   繁体   中英

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?

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM