【C语言难弄关键字2】----union

【C语言难弄关键字2】----union

1.union关键字用法同struct

union可以存放多个数据成员中的一种,而不是为每一个数据成员分配空间,在union中,所有数据成员共用一个空间,同一时间只能存储其中一个数据成员,所有数据成员具有相同的起始地址。

[klaus@localhost keyword_study]$ cat union.c
#include <stdio.h>

int main(int argc, char *charv[])
{

union StateMate
{
  char character;
  int number;
  char *str;
  double exp;
};

        return 0;
}
[klaus@localhost keyword_study]$

一个union只配置一个足够大的空间来容纳最大长度的数据成员,这里StateMate的大小也就是double数据类型的大小。

2.通过union确定大小端系统存储模式

存储模式
大端模式(Big_endian) :字数据的高字节存储在低地址中,而字数据的低字节存放在高地址中。
小端模式(Little_endian):字数据的高字节存储在高地址中,而字数据的低字节存放在低地址中。

编写一个c函数,若处理器是Big_endian,则返回0,若处理器是Little_endian,则返回1;

[klaus@localhost keyword_study]$ cat sysCheckEndian.c
#include <stdio.h>

int checkSystem()
{
        union check
        {
          int i;
          char ch;
        }c;
        c.i=1;
        return (c.ch==1);
}

int main(int argc, char *charv[])
{
        if(checkSystem())
         printf("Little_endian\n");
        else
         printf("Big_endian\n");
        return 0;
}
[klaus@localhost keyword_study]$ gcc sysCheckEndian.c
[klaus@localhost keyword_study]$ ./a.out
Little_endian
[klaus@localhost keyword_study]$

3.x86系统测试

x86系统上测试,我的测试环境暂时不能得出结果

[klaus@localhost keyword_study]$ cat x86Endian.c
#include <stdio.h>

int main(int argc, char *charv[])
{
        int a[5]={1,2,3,4,5};
        int *ptr1=(int *)(&a+1);
        int *ptr2=(int *)((int)a+1);

        printf("%x,%x",ptr1[-1],*ptr2);
        return 0;
}
[klaus@localhost keyword_study]$ gcc x86Endian.c
x86Endian.c: In function ‘main’:
x86Endian.c:7: warning: cast from pointer to integer of different size
x86Endian.c:7: warning: cast to pointer from integer of different size
[klaus@localhost keyword_study]$

大家有机会可以编译看一下。

注:本篇文章学习来自《c语言深度剖析》,侵权必删。

发布了80 篇原创文章 · 获赞 86 · 访问量 9万+

猜你喜欢

转载自blog.csdn.net/klaus_x/article/details/82961578
今日推荐