Angus
Angus

Reputation: 12621

Questions on compound literals in C

COMPOUND LITERALS:

#include<stdio.h>

struct s{
 int x;
 int y;
};

int main(){
 int j = 5;
 printf("\n &j : %p \n",&j);
 struct s *p = &(struct s){j++};
 printf("\n p : %p &j : %p x : %d y : %d \n",p,&j,p->x,p->y);
 return 0;
}

o/p:
-----
&j : 0x7fff416b74ec 
 p : 0x7fff416b74d0 &j : 0x7fff416b74ec x : 5 y : 0

a] Why is p not holding the address of j ?

b] why is j not being typecast to struct s ?

Upvotes: 1

Views: 137

Answers (4)

haccks
haccks

Reputation: 106012

The statement

struct s *p = &(struct s){j++}; // compiler should raise a warning 

is incomplete. It should be like

struct s *p = &(struct s){.x = j++};  

or

struct s *p = &(struct s){.y = j++};  

The uninitialized member will be set ti 0 by default.

The reason that p doesn't hold the address of j is clear that p is holding the address of new object (compound literal), not the address of j itself.

Upvotes: 1

Manisha  Bano
Manisha Bano

Reputation: 1903

for your first question,, p is of struct type and j is of integer type and you have to make the pointer and the variable of same datatype... like int *p = &j; //where j is of int type.

Upvotes: 0

Manisha  Bano
Manisha Bano

Reputation: 1903

j is of integer type(primitive data) and you are trying to convert it into complex datatype(object).. thus, you are trying to do boxing and unboxing.. which are not concepts of c or c++...

Upvotes: -1

ars
ars

Reputation: 707

a) p not holds the address of j because p point to freshly created structure. if you want, that p point to j, you should write:

int * p = &j;

b) j is int local (stack) variable, so i see no way, how it can be cast into the structure.

@David C. Rankin, i've reformed my answer

Upvotes: 1

Related Questions