Difference between “pointer to int” and “pointer to array of ints”

前端 未结 8 1458
甜味超标
甜味超标 2020-11-29 02:48
int main()
{
    int (*x)[5];                 //pointer to an array of integers
    int y[6] = {1,2,3,4,5,6};    //array of integers
    int *z;                              


        
8条回答
  •  有刺的猬
    2020-11-29 03:41

    Hope this code helps:

    int main() {
    
        int arr[5] = {4,5,6,7,8};        
        int (*pa)[5] = &arr;
        int *pi = arr;
    
        for(int i = 0; i< 5; i++) {
            printf("\n%d %d", arr[i], (*pa)[i]);    
        }
    
        printf("\n0x%x -- 0x%x", pi, pa);
        pi++;
        pa++;
        printf("\n0x%x -- 0x%x", pi, pa);
    }
    

    prints the following:

    4 4
    5 5
    6 6
    7 7
    8 8
    0x5fb0be70 -- 0x5fb0be70
    0x5fb0be74 -- 0x5fb0be84 
    

    UPDATE: You can notice that pointer to integer incremented by 4 bytes (size of 32 bit integer) whereas pointer to array of integer incremented by 20 bytes (size of int arr[5] i.e. size of 5 int of 32 bit each). This demonstrates the difference.

提交回复
热议问题