问题描述
您好,
我正在通过UNIX网络编程通过R.Stevens并坚持使用
以下代码,确定正在运行的主机的endiannes:
#include< stdio.h>
#include< stdlib.h>
#define CPU_VENDOR_OS" i686-pc-linux-gnu"
int main(无效)
{
union {
short s;
char c [sizeof (短)];
}联合国;
un.s = 0x0102;
printf("%s:" ;,CPU_VENDOR_OS);
if(sizeof(short)== 2){
if(un.c [0] == 1&& un.c [1] == 2)
printf(" big-endian \ n");
else if(un.c [0] == 2& & un.c [1] == 1)
printf(" little-endian \ n");
else
printf(unknown\\\
);
}其他
printf(" sizeof(短)=%d \ n",sizeof(短)) ;
退出(0);
}
我没有得到的是怎么样的un.c [0]和un.c [1]都包含
已被初始化的内容,即0x0102。它是''union''的一个特性吗?
为什么我们不能用''struct'来检查字节在内存中的放置方式?
提前致谢!
最诚挚的问候,罗马马沙克。电子邮件:
Hello,
I''m going through the "UNIX network programming" by R.Stevens and stuck with
the following code, determining the endiannes of a host it is running on:
#include <stdio.h>
#include <stdlib.h>
#define CPU_VENDOR_OS "i686-pc-linux-gnu"
int main(void)
{
union {
short s;
char c[sizeof(short)];
} un;
un.s = 0x0102;
printf("%s: ", CPU_VENDOR_OS);
if (sizeof(short) == 2) {
if (un.c[0] == 1 && un.c[1] == 2)
printf("big-endian\n");
else if (un.c[0] == 2 && un.c[1] == 1)
printf("little-endian\n");
else
printf("unknown\n");
} else
printf("sizeof(short) = %d\n", sizeof(short));
exit(0);
}
What I don''t get is how come that un.c[0] and un.c[1] both contain what has
been un.s initialized, i.e. 0x0102. Is it a feature of ''union''?
Why could not we use ''struct'' to check how bytes are placed in memory ?
Thanks in advance!
With best regards, Roman Mashak. E-mail: mr*@tusur.ru
推荐答案
结构中的元素都占据独立且不同的元素
件记忆,但联盟的元素都占据了一个共同的片段。记忆。
-
Morris Dovey
DeSoto Solar
德索托,爱荷华州美国
这篇关于关于工会的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!