Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
388 views
in Technique[技术] by (71.8m points)

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

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 it print? I'm expecting the garbage value here but the output is 1.
(for which I'm concluding that initializing this way pointer array i.e ptr[10] would start pointing to elements of a[10] in order).

But what about this code fragment:

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

It is giving the segmentation fault.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

int *ptr[10];

This is an array of 10 int* pointers, not as you would assume, a pointer to an array of 10 ints

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 ints


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...