Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C - Is struct variable a pointer?

Tags:

c

struct

I have searched a lot but i could't find any topic about this. My question is: Is struct variable a pointer? And if every input are stored in struct members' addresses, so what are struct variable used for?

This is the code i used for checking struct variable, when i printed what is stored in the variable, it gave me another address but i couldn't figure what that address is used for.

Here is my code and its output:

 struct test
 {
 int a;
 int b;
 char c;
 }; 

 int main()
 {

 struct test f;

 printf("%u", &f);
 printf("\n%d", f);
 printf("\n%u", &f.a);
 printf("\n%u", &f.b);
 }

Output:

6487616

6487600

6487616

6487620

like image 626
Thuan Nguyen Avatar asked Oct 20 '25 10:10

Thuan Nguyen


1 Answers

Short answer: No.

Long version: All your print statements in the aforesaid program invoke undefined behaviour, as the supplied argument does not match the conversion specifier.

To elaborate, to print a pointer, you need to use %p conversion specifier, with a cast to void * for the argument.

There is no generic (one-for-all sort) format specifier for a structure variable. You need to choose individual members (or member of member, thereof) which has a corresponding format specifier, and pass that as the argument.

That said, regarding the first member and the access,

[...] A pointer to a structure object, suitably converted, points to its initial member (or if that member is a bit-field, then to the unit in which it resides), and vice versa. [...]

like image 177
Sourav Ghosh Avatar answered Oct 22 '25 01:10

Sourav Ghosh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!