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 ?
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.
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
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.
j是整数类型(原始数据),并且您尝试将其转换为复杂数据类型(对象)..因此,您正在尝试进行装箱和拆箱..这不是c或c ++的概念...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.