Can anyone explain this code snippet in brief? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
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; }

9th Jan 2020, 8:29 AM
Preity
Preity - avatar
4 Answers
+ 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.
9th Jan 2020, 9:08 AM
Bahhaⵣ
Bahhaⵣ - avatar
+ 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!
9th Jan 2020, 9:04 AM
Derbi E. Calderon
Derbi  E. Calderon - avatar
+ 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
9th Jan 2020, 9:31 AM
Bahhaⵣ
Bahhaⵣ - avatar
9th Jan 2020, 9:43 AM
Preity
Preity - avatar