C puzzles详解【6-8题】

时间:2023-03-08 20:22:09
C puzzles详解【6-8题】

第六题

  #include<stdio.h>
int main()
{
int a=;
switch(a)
{
case '':
printf("ONE\n");
break;
case '':
printf("TWO\n");
break;
defa1ut:
printf("NONE\n");
}
return ;
}

题目讲解:

“defalut”拼写错误。

注意a为int型,case后的’1’,’2’为char型。

第七题

The following C program segfaults of IA-, but works fine on IA-.

int main()
{
int* p;
p = (int*)malloc(sizeof(int));
*p = ;
return ;
}

知识点讲解:

IA-64和IA-32属于完全不同的处理器架构,两者的指令集不相互兼容。

http://wangcong.org/blog/archives/291的解释为“IA-64是RISC,不能访问未对齐的地址”,不太明白。

第八题

Here is a small piece of program(again just  lines of program) which counts the number of bits set in a number.
Input Output
()
()
() int CountBits (unsigned int x )
{
static unsigned int mask[] = { 0x55555555,
0x33333333,
0x0F0F0F0F,
0x00FF00FF,
0x0000FFFF
} ; int i ;
int shift ; /* Number of positions to shift to right*/
for ( i =, shift =; i < ; i ++, shift *= )
x = (x & mask[i ])+ ( ( x >> shift) & mask[i]);
return x;
}
Find out the logic used in the above program.

题目讲解:

计算一个int型参数二进制模式中1的个数。传统的算法要经过32次循环,

此算法最多只需5次。

以x = 1234为例,

1234的二进制表示为:

0000 0100 1101 0010

第一步:相邻2位相加

0000 0100 1101 0010 ---> 0000 0100 1001 0001

第二步:相邻4位相加

0000 0100 1001 0001 ---> 0000 0001 0011 0001

第三步:相邻8位相加

0000 0001 0011 0001 ---> 0000 0001 0000 0100

第四步:相邻16位相加

0000 0001 0000 0100 ---> 0000 0000 0000 0101

第五步:相邻32位相加

无需继续计算。

结果为5。

至于这么做为什么恰巧得到的是1的个数,不解。