Pointer to an array and Array of pointers

前端 未结 6 2031
感动是毒
感动是毒 2020-12-22 00:47

As I am just a learner, I am confused about the above question. How is a pointer to an array different from array of pointers? Please explain it to me, as I will have to exp

6条回答
  •  礼貌的吻别
    2020-12-22 01:29

    Pointer to an array

    int a[10];
    int (*ptr)[10];
    

    Here ptr is an pointer to an array of 10 integers.

    ptr = &a;
    

    Now ptr is pointing to array of 10 integers.

    You need to parenthesis ptr in order to access elements of array as (*ptr)[i] cosider following example:

    Sample code

    #include
    int main(){
      int b[2] = {1, 2}; 
      int  i;
      int (*c)[2] = &b;
      for(i = 0; i < 2; i++){
         printf(" b[%d] = (*c)[%d] = %d\n", i, i, (*c)[i]);
      }
      return 1;
    }
    

    Output:

     b[0] = (*c)[0] = 1
     b[1] = (*c)[1] = 2
    

    Array of pointers

    int *ptr[10];
    

    Here ptr[0],ptr[1]....ptr[9] are pointers and can be used to store address of a variable.

    Example:

    main()
    {
       int a=10,b=20,c=30,d=40;
       int *ptr[4];
       ptr[0] = &a;
       ptr[1] = &b;
       ptr[2] = &c;
       ptr[3] = &d;
       printf("a = %d, b = %d, c = %d, d = %d\n",*ptr[0],*ptr[1],*ptr[2],*ptr[3]);
    }
    

    Output: a = 10, b = 20, c = 30, d = 40

提交回复
热议问题