Does an Array variable point to itself?

前端 未结 4 1822
猫巷女王i
猫巷女王i 2021-01-23 11:14

I tried some code to check the behavior of array and pointers. Its as follows.

#include 
main(){
int s[]={1,2};
int *b=s;
printf(\"%d, %d, %d\\n\"         


        
4条回答
  •  星月不相逢
    2021-01-23 11:52

    OK, let say the following is how the memory looks when you execute

    int s[]={1,2};
    int *b=s;
    
    s[]
    +-----+-----+
    |  1  |  2  |
    +-----+-----+
    100   104 
    ^
    |
    |  int *b = &s
    +-----+
    | 100 |
    +-----+
    200
    

    s is an array. What that means is, it is a contiguous memory location which is associated with a variable s and each element is accessed by offsetting the array variable name.

    So when you use s it actually boils down to the address of the array (which is 100 in this case). And when you do *s, it boils down to *(s+0) which is equivalent of s[0] and so *s represents the contents stored in the zeroth location (in this case s[0] is 1). When do do an &s, this will print the address of the s (which is100` in this case).

    Note that, here s and &s represents an address; *s and s[x] represents an integer.

    The same applies to the pointer. So, b prints the content it has, which is the address of s (which is 100 in this case). &b prints the address of b, which is 200 in this case. And, *b prints the content of the first element of the array s which is 1.

    I have modified you program to make it print the address.

    #include 
    
    int main(void)
    {
        int s[]={1,2};
        int *b=s;
        printf("%p, %p, %d\n", (void *)s, (void *)&s, *s);
        printf("%p, %p, %d\n", (void *)b, (void *)&b, *b);
        return 0;
    }
    

    Output:

    0xbfc4f3e4, 0xbfc4f3e4, 1
    0xbfc4f3e4, 0xbfc4f3ec, 1
    

    EDIT: %p expects void *. Added the same!

提交回复
热议问题