#include <stdio.h>
#include<stdlib.h>
struct try {
int x,*x_Ptr;
float y,*y_Ptr;
char q,*q_Ptr;
}; //integer, float character variables and their pointers are defined in the structures.
int main (void){
struct try den1;
struct try den2;
struct try den3;
den1.x=7;
den2.x=8;
den1.y=-.14;
den2.y=23.45;
den3.q='A';
den1.x_Ptr=&den1.x; //pointer assignments for integer.
den2.x_Ptr=&den2.x;
den1.y_Ptr=&den1.y; //pointer assignments for float.
den2.y_Ptr=&den2.y;
den3.q_Ptr=&den3.q; //pointer assignments for character.
system("clear");
printf("The integer in den1:%d\nThe integer in den2:%d\nThe address of integer in den1:%p\nThe address of integer in den2:%p\nThe pointer address of integer in den1:%p\nThe pointer address of integer in den2:%p\n",den1.x,den2.x,&den1.x,&den2.x,&*den1.x_Ptr,&*den2.x_Ptr);
printf("\n");
printf("The float in den1:%f\nThe float in den2:%f\nThe address of float in den1:%p\nThe address of float in den2:%p\nThe pointer address of float in den1:%p\nThe pointer address of float in den2:%p\n",den1.y,den2.y,&den1.y,&den2.y,&*den1.y_Ptr,&*den2.y_Ptr);
printf("\n");
printf("The character in den3:%c\nThe address of character in den3:%p\nThe pointer address of character in den3:%p\n",den3.q,&den3.q,&*den3.q_Ptr);
printf("\n");
printf("\nThe whole address of the first struct{...\n...\n...\n...\t\t\t}den1:%p\n",&den1);
printf("\nThe whole address of the second struct{...\n...\n...\n...\t\t\t}den2:%p\n",&den2);
printf("\nThe whole address of the second struct{...\n...\n...\n...\t\t\t}den3:%p\n",&den3);
return 0;
}
我意识到struct中整数之一的地址与struct的地址相同。是什么原因?
答案 0 :(得分:0)
我意识到struct中整数之一的地址与struct的地址相同。是什么原因?
因为他们有相同的地址。
该结构占用其所有成员的组合空间。对象的地址是其第一个字节的地址。 den1.x是den1的第一个成员,因此它从den1的相同字节开始。
一张图片值一千字:
address data
00123458 07 \ <- address of x \ <- address of den1
00123459 00 | |
0012345a 00 | space used by x |
0012345b 00 / | space
0012345c 58 \ <- address of x_ptr | used
0012345d 34 | | by
0012345e 12 | space used by x_ptr | den1
0012345f 00 / |
00123460 29 \ <- address of y |
00123461 5c | |
00123462 0f | space used by y |
00123463 be / |
00123464 60 \ <- address of y_ptr |
00123465 34 | |
00123466 12 | space used by y_ptr |
00123467 00 / |
00123468 41 } address of c |
00123469 00 \ (c only takes 1 byte) |
0012346a 00 | padding so that c_ptr starts |
0012346b 00 / on a multiple of 4 bytes |
0012346c 68 \ <- address of c_ptr |
0012346d 34 | |
0012346e 12 | space used by c_ptr |
0012346f 00 / /