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

前端 未结 8 1505
甜味超标
甜味超标 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:22

    #include
    
    int main(void)
    {
        int (*x)[6];                 //pointer to an array of integers
        int y[6] = {11,22,33,44,55,66};    //array of integers
        int *z;                      //pointer to integer
        int i;
    
        z = y;
        for(i = 0;i<6;i++)
            printf("%d ",z[i]);
        printf("\n");
    
        x = &y;
    
        for(int j = 0;j<6;j++)
            printf("%d ",*(x[0]+j));
    
        return 0;
    }
    

    //OUTPUT::

    11 22 33 44 55 66

    11 22 33 44 55 66

    Pointer to an array are best suitable for multi-dimensional array. but in above example we used single dimension array. so, in the second for loop we should use (x[0]+j) with * to print the value. Here, x[0] means 0th array. And when we try to print value using printf("%d ",x[i]); you will get 1st value is 11 and then some garbage value due to trying to access 1st row of array and so on.

提交回复
热议问题