Search code examples
cstructure

in structure how values get stored?


if a have a structure say

struct first
{
   int a;
   int b;
 };

now if i create its object

int main(){
struct first ob1,ob2;

ob1.a=5;
printf("%u  %u",&ob1,&(ob1.a));  //prints same address
printf("%d  %d",ob1,(ob1.a)); //  5,garbage value
return 0;}

my professor said that ob1 is a pointer to a structure. I want to know what address does ob1 and ob1.a also what value they store?

Also in c++ we have this pointer to assign value to ob1.a and ob2.a. In C how does compiler know in which object to store value ?


Solution

  • ob1 is in no way a pointer. It is a structure.

    Since a is the first field of struct first, &ob1 and &ob1.a are the same address (but have different types).

    In C, the compiler knows which object to store to because you have to tell it. In your case, you said ob1.a or ob2.a respectively.

    Editorial note: use %p to print pointers, and don't try to pass a structure to printf at all.