+ 1
I do not understand this challenge in C
#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; } what the p->x and (p + 2) -> y mean? please help! thank you
5 Answers
+ 2
if p struct pointer then it's elements are accessed by p -> element;
So there p -> x refers to p[0] -> x
and p[0] is {1, 2};
since struct has { x, y} which values are stored on p1[] array sequentially..
p +2 points to p[2] =>{5} of {x, y} , y is not assinged any value so default is 0;
Here is clear code for the above program: hope it helps to understand clearly.
#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+0)->x, (p + 2)->y);
}
+ 3
AnađșÄuricađŒđž arrow operator used to dereferencing a pointer, so the syntax is the same as (*ptr). Dereferencing a pointer means to get the value of that address and as Jayakrishnađźđł mentioned y had no assignment.
+ 2
Jayakrishnađźđł
so it goes like this
struct point p1[] = { {x,y}, {x,y}, {x}}
?
and
p -> x => 1
p -> y => 2
(p + 1) -> x => 3
(p + 1) -> y => 4
(p + 2) -> x => 5
(p + 2) -> y => 0
+ 2
Yes.
p1[] array is array of 'point ' structure.
and each structure holding 2 variables (x, y) .
+ 1
The output is 1 0