1

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 ?

Jayesh Bhoi
  • 24,694
  • 15
  • 58
  • 73
Angus
  • 12,133
  • 29
  • 96
  • 151

4 Answers4

1

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.

Community
  • 1
  • 1
haccks
  • 104,019
  • 25
  • 176
  • 264
  • 1
    Well, there is `1/2` a compound literal. The warning is of the type `warning: missing initializer for field ‘y’ of ‘struct s’`. So the statement `struct s *p = &(struct s){j++};` is treated as a compound literal with partial assignment of `p->x=5` with `p->y defaulting to 0` as I understand it. So the first statement may better read as `There is no complete compound literal in your code.` – David C. Rankin Aug 16 '14 at 07:12
  • Please revise our answer. You say "*There is no compound literal in your code.*" and you also say: "*... `p` is holding the address of compound literal*". Decide: "*To be or not to be?*" – alk Aug 16 '14 at 09:54
1

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

ars
  • 707
  • 4
  • 14
  • 2
    You need to add more than copy/paste from the [**Compound Literals**](https://gcc.gnu.org/onlinedocs/gcc-3.2/gcc/Compound-Literals.html) of the gcc manual (or at least give attribution) – David C. Rankin Aug 16 '14 at 07:15
0

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.

Manisha Bano
  • 1,853
  • 2
  • 22
  • 34
-1

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++...

Manisha Bano
  • 1,853
  • 2
  • 22
  • 34