0
Can anyone explain this code snippet in brief?
#include <stdio.h> struct Ournode{ char x, y, z; }; int main() { struct Ournode p = {'1', '0', 'a' + 2}; struct Ournode *q = &p; printf("%c, %c", *((char *)q+1), *((char *)q+2)); return 0; }
4 Antworten
+ 2
a struct with three members x,y,z
p is a struct Ournode type .
q is pointing to p memory address .
the values of x,y,z are in consecutive memory addresses .
when you do operations with pointers
it means you are jumping between addresses in memory.
q+0 --> 1 / q+1 --> 0 q+3 --> 'a'+2
char 'a' + 2 = 'c' /[abcdefg...z]
'a' + 3 = d and so on.
+ 2
I can try.
You make a struct named Ournode.
Then you declare p of type Ournode with the char values 1 , 0 and c. ( c since you're adding 2 and the ascii value of 'a' plus 2 is c)
Then you declare a pointer, q, of type Ournode that points to p.
Then you use said pointer to access the values in p via derefrenece , so your output would be 0 and c.
Hope that helps!
+ 2
check the output of this, it prints the memory addresses of x, y, z
printf("%p, %p, %p",q+0, q+1, q+2);
when you add * (dereference as Derbi E. Calderon said) and %c instead of %p it prints the values
+ 2
Thanks bahha🐧 Derbi E. Calderon 👍