Difference between *ptr[10] and (*ptr)[10]

前端 未结 6 1407
自闭症患者
自闭症患者 2020-12-04 17:29

For the following code:

    int (*ptr)[10];
    int a[10]={99,1,2,3,4,5,6,7,8,9};
    ptr=&a;
    printf(\"%d\",(*ptr)[1]);

What should

6条回答
  •  無奈伤痛
    2020-12-04 17:46

    int (*ptr)[10];
    

    is a pointer to an array of 10 ints.

    int *ptr[10];
    

    is an array of 10 pointers.

    Reason for segfault:

    *ptr=a; printf("%d",*ptr[1]);

    Here you are assigning the address of array a to ptr which would point to the element a[0]. This is equivalent to: *ptr=&a[0];

    However, when you print, you access ptr[1] which is an uninitialized pointer which is undefined behaviour and thus giving segfault.

提交回复
热议问题