一道难懂的C语言程序求高手解答

来源:百度知道 编辑:UC知道 时间:2024/05/23 02:19:42
如下:

union ss
{ int i;
char c[2];
};
main()
{ union ss x;
x.c[0]=10;
x.c[1]=1;
printf("%d",x.i);
}
结果是261,我百思不得其解,为什么char类型的‘1’会变成int型的261?

Firstly x is a union, so x.i and x.c[2] share a 16 bits memory.

And then you store integer 10 in x.c[0], and integer 1 in x.c[1],

So
x.c[0] at low 8 bits is 00001010
x.c[1] at high 8 bits is 00000001

Data in this 16 bits memory is 00000001 00001010

So the result is 266.

Thus I don't know why you get a 261 either, I use TurboC 2.0 under windows XP.

因为你打印的是i,i这个公用体变量并没有被赋过值,出现的是一个随即数,我这里运行出现的是一个很大的数。
你打印c[0],c[1]看看,没问题的

union ss
{ int i;
char c[2];
};
main()
{ union ss x;
x.c[0]=10;
x.c[1]=1;
printf("%d %d",x.c[0],x.c[1]);
}

上面英文版的说的对
c[0]=0000 1010是低八位,c[1]=0000 0001是高八位
这样0000 0001 0000 1010就是266,你的261绝对是打错了.

同样如果c[0]=10=0000 1010,c[1]=2=0000 0010
二者和起来0000 0010 0000 1010就是522

依次类推当c[1]=3时结果为778
当c[1]=4时结果为1034
……
自己验证吧

答案应该是266
为什么会出现你的结果呢?可能有点错吧<