Difference between *ptr[10] and (*ptr)[10]
int *ptr[10];
This is an array of 10 int*
pointers, not as you would assume, a pointer to an array of 10 int
s
int (*ptr)[10];
This is a pointer to an array of 10 int
It is I believe the same as int *ptr;
in that both can point to an array, but the given form can ONLY point to an array of 10 int
s
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.
int(*)[10]
is a pointer to an int array with 10 members. i.e it points to int a[10]
.
where as int *[10]
is array of integer pointers
#include <stdio.h>
int main()
{
int *ptr[10];
int a[10]={0,1,2,3,4,5,6,7,8,9};
printf("\n%p %p", ptr[0], a);
*ptr=a; //ptr[0] is assigned with address of array a.
printf("\n%p %p", ptr[0], a); //gives you same address
printf("\n%d",*ptr[0]); //Prints zero. If *ptr[1] is given then *(ptr + 1) i.e ptr[1] is considered which is uninitialized one.
return 0;
}