结构体中的成员并不一定是连续存储地存储在内存单元中 使用共同体可以节约存储空间

 小结:

1、结构体成员的地址顺序同结构体定义时的成员的先后顺序;

1、 

Q

为什么不能用运算符==或!=来对结构体进行比较

A

结构体中的成员并不一定是连续存储地存储在内存单元中

2、

对结构体成员访问

.  structure member operator 结构体成员运算符 .

-> structure pointer operator 结构体指针运算符 ->

struct card {

char *face;

char *suit;

} aCard,deck[52],*cardPtr;

aCard.suit;

cardPtr->suit;等价于(*cardPtr).suit; 优先级 .>*

3、

#include <stdio.h>
union number {
int x;
double y;
};
int main(void) {
union number value;
value.x = 100;
printf("%d,%f\n",value.x,value.y);
value.y = 100.0;
printf("%d,%f\n",value.x,value.y);
}

与结构体一行,共同体也是一种派生类型。

共同体的成员共享同一个存储空间。

123,2426809083006282900000000000000000000000000000000000000000000000000.000000
0,100.000000
请按任意键继续. . .

 每次只能访问共同体的一个成员;

存储一个共同体所用的字节总数,必须保证至少足以能够容纳其最大的成员。

#include <stdio.h>
union number {
int x;
double y;
};
int main(void) {
union number value;
value.x = 123;
printf("%d,%f\n",value.x,value.y);
printf("%d,%d,%d\n",&value,&(value.x),&(value.y));
value.y = 100.0;
printf("%d,%f\n",value.x,value.y);
printf("%d,%d,%d\n",&value,&(value.x),&(value.y));
}

123,-28473359069967665000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
000000000000000.000000
37814048,37814048,37814048
0,100.000000
37814048,37814048,37814048
请按任意键继续. . .

4、对比结构体成员地址

#include <stdio.h>
struct card {
char *face;
char *suit;
};
int main(void) {
struct card aCard,*cardPtr;
aCard.face="Ace";
aCard.suit="Spades";
cardPtr=&aCard;
printf("%s of %s \n%s of %s \n",aCard.face,aCard.suit,cardPtr->face,cardPtr->suit);
printf("%d,%d,%d\n%d,%d,%d",&aCard,&aCard.face,&aCard.suit,cardPtr,&cardPtr->face,&cardPtr->suit);
return 0;
}

Ace of Spades
Ace of Spades
37814048,37814048,37814052
37814048,37814048,37814052请按任意键继续. . .

#include <stdio.h>
struct card {
char *suit;
char *face;
};
int main(void) {
struct card aCard,*cardPtr;
aCard.face="Ace";
aCard.suit="Spades";
cardPtr=&aCard;
printf("%s of %s \n%s of %s \n",aCard.face,aCard.suit,cardPtr->face,cardPtr->suit);
printf("%d,%d,%d\n%d,%d,%d",&aCard,&aCard.face,&aCard.suit,cardPtr,&cardPtr->face,&cardPtr->suit);
return 0;
}

Ace of Spades
Ace of Spades
37814048,37814052,37814048
37814048,37814052,37814048请按任意键继续. . .

猜你喜欢

转载自www.cnblogs.com/yuanjiangw/p/10500214.html
今日推荐