Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the different between args and &args?

Tags:

arrays

c

Here is my code snip

    #include <stdio.h>

    void change(int a[]){
        printf("%p\n",&a);
    }

   int main(){
       int b[] = {1,2} ;
       printf("%p\n",&b);
       change(b);
       return 0;
   }

I run it and it get the result following

    0x7fff5def1c60
    0x7fff5def1c38

As we can see the actual parameter address is defferent from the formal parameter address Then I edited my following

    #include <stdio.h>

    void change(int a[]){
        printf("%p\n",a);
    }

    int main(){
        int b[] = {1,2} ;
        printf("%p\n",b);
        change(b);
        return 0;
    }

Then I get the results

    0x7fff56501c60
    0x7fff56501c60

So it seems that the actual parameter and the formal parameter have the same address. I am confused that what's the different between &a and a(a is a array),and why I get the different address from the first snippet? Thanks!

like image 302
Gmx Avatar asked Feb 11 '23 12:02

Gmx


1 Answers

In:

printf("%p\n",&b);

you are printing the address to the first array cell.

In:

change(b);

and specifically in:

void change(int a[]){
    printf("%p\n",&a);
}

you are printing the address of the variable a which in itself is a decayed pointer. So it is semantically equivalent to:

void change(int* a){
    printf("%p\n",&a);
}

To retrieve the array first cell you would need to write the function as:

void change(int* a){
    printf("%p\n", a);
    //            ^^
}
like image 94
Shoe Avatar answered Feb 20 '23 12:02

Shoe