+ 1
Can someone explain me the principle behind the code below? Why does the (p+2)->y is equal to 0?
Hi! I know this code is correct but I don't know how. Kindly help me in understanding this. Why does the (p+2)->y is equal to 0? #include<stdio.h> struct point { int x; int y}; void foo(struct point*); int main(){ struct point p1[]={1,2,3,4,5}; foo(p1); } void foo(struct point p[]){ printf("%d %d\n", p->x, (p+2)->y); return 0; } Thanks in advance for your answers friends.
5 Answers
+ 2
Maria Loida M Canada the short answer to your question is: because it is an object that has static storage duration.
The long answer is given by the following links:
https://stackoverflow.com/questions/10828294/c-and-c-partial-initialization-of-automatic-structure
https://stackoverflow.com/questions/13251083/the-initialization-of-static-variables-in-c
https://stackoverflow.com/questions/201101/how-to-initialize-all-members-of-an-array-to-the-same-value
PS: This code is correct, but it is hard to understand (this is often true for C quiz questions; you should not use them as a reference for good coding style). For a better readable code see the answer by Mustafa K.
+ 1
Thanks Mustafa K., now I understand it.
+ 1
Maria Loida M Canada It looks like difficult but it's simple array is a pointer with chunk of memory when we write name of array it mean the base address of array or we say first element address of array if we write p+2 mean the increment 2 time of the base adrres and arrow operator is goes to those memory element which arrow point in above example p+2->y mean goes 3 element and give the value of y
I hope u get it and y is 0 because when u initialise your array 1,2 goes first element and 3,4 goes 2nd element and 3 element remain 5 and blank and blank represent 0 my english is not good then avoid grammer mistake
0
y value does not exist.
You should be initializing your point array properly.
edit:
You should be using this syntax.
struct point p1[] = { { .x = 1, .y = 9}, {.x = 9, .y = 3} };
this creates an array with 2 points with values 1,9 and 9,3 respectively.
0
Each `point` structure instance requires 2 `int` values (for its <x> and <y> field). Your `point` array <p1> only initialized with 5 elements, so the 3rd element in that array is a corrupt instance because it is missing a value for its <y> field. To verify this, you can add the 6th element into array <p1>, and check the output.
Actually value of zero as the 3rd element's <y> value is not a certainty, this value is rather unpredictable.