Different Pointer Arithmetic Results when Taking Address of Array

后端 未结 5 2072
北恋
北恋 2020-12-25 10:14

Program:

#include

int main(void) {
    int x[4];
    printf(\"%p\\n\", x);
    printf(\"%p\\n\", x + 1);
    printf(\"%p\\n\", &x);
    p         


        
5条回答
  •  执笔经年
    2020-12-25 10:30

    Even though x and &x evaluate to the same pointer value, they are different types. Type of x after it decays to a pointer is int* whereas type of &x is int (*)[4].

    sizeof(x) is sizeof(int)*4.

    Hence the numerical difference between &x and &x + 1 is sizeof(int)*4.

    It can be better visualized using a 2D array. Let's say you have:

    int array[2][4];
    

    The memory layout for array is:

    array
    |
    +---+---+---+---+---+---+---+---+
    |   |   |   |   |   |   |   |   |
    +---+---+---+---+---+---+---+---+
    
    array[0]        array[1]
    |               |
    +---+---+---+---+---+---+---+---+
    |   |   |   |   |   |   |   |   |
    +---+---+---+---+---+---+---+---+
    

    If you use a pointer to such an array,

    int (*ptr)[4] = array;
    

    and look at the memory through the pointer, it looks like:

    ptr             ptr+1
    |               |
    +---+---+---+---+---+---+---+---+
    |   |   |   |   |   |   |   |   |
    +---+---+---+---+---+---+---+---+
    

    As you can see, the difference between ptr and ptr+1 is sizeof(int)*4. That analogy applies to the difference between &x and &x + 1 in your code.

提交回复
热议问题