C谜题解释

原创 2013年12月02日 23:13:20

看到了这个网址http://www.gowrikumar.com/c/,作者收集了一系列网上和自己所遇到的C语言有趣的东西,我感觉挺像<Java解惑>的风格,我下面就尝试解决一下作者提出的问题.

第一题

The expected output of the following C program is to print the elements in the array. But when actually run, it doesn't do so.

#include<stdio.h>

#define TOTAL_ELEMENTS (sizeof(array) / sizeof(array[0]))
int array[] = {23,34,12,17,204,99,16};

int main()
{
		int d;

		for(d=-1;d <= (TOTAL_ELEMENTS-2);d++)
				printf("%d\n",array[d+1]);

		return 0;
}

Find out what's going wrong.
这道题作者给出了提示,因为sizeof操作符返回的是size_t类型,一般情况下size_t是无符号类型,所以在for循环中当-1与(TOTAL_ELEMENTS-2)比较时,-1首先被转换成无符号数来进行比较,此时-1被解释为一个很大的整数,大于(TOTAL_ELEMENTS-2)的值,所以代码什么也不输出,与程序作者本意相违背.

第二题:

I thought the following program was a perfect C program. But on compiling, I found a silly mistake. Can you find it out (without compiling the program :-) ?

#include<stdio.h>

void OS_Solaris_print()
{
	printf("Solaris - Sun Microsystems\n");
}

void OS_Windows_print()
{
	printf("Windows - Microsoft\n");

}
void OS_HP-UX_print()
{
	printf("HP-UX - Hewlett Packard\n");
}

int main()
{
	int num;
	printf("Enter the number (1-3):\n");
	scanf("%d",&num);
	switch(num)
	{
		case 1:
			OS_Solaris_print();
			break;
		case 2:
			OS_Windows_print();
			break;
		case 3:
			OS_HP-UX_print();
			break;
		default:
			printf("Hmm! only 1-3 :-)\n");
			break;
	}

	return 0;
}
这道题比较简单,就是函数OS_HP-UX_print()中间不能有符号-,作者也给出了提示.

第三道题:

What's the expected output for the following program and why?

enum {false,true};

int main()
{
        int i=1;
        do
        {
                printf("%d\n",i);
                i++;
                if(i < 15)
                        continue;
        }while(false);
        return 0;
}
作者也给出了提示,在K&R的书中提到,在while与do while语句中,continue语句的执行意味着立即执行测试部分.所以上述程序只输出1,同时要注意程序没有导入stdio.h头文件,在一些编译器上会出错.

第四道题:

The following program doesn't "seem" to print "hello-out". (Try executing it)

  #include <stdio.h>
  #include <unistd.h>
  int main()
  {
          while(1)
          {
                  fprintf(stdout,"hello-out");
                  fprintf(stderr,"hello-err");
                  sleep(1);
          }
          return 0;
  }

What could be the reason?
这道题我不明白,应该是与多线程之类的有关系(以后再弄)

第五道题:

  #include <stdio.h>
  #define f(a,b) a##b
  #define g(a)   #a
  #define h(a) g(a)

  int main()
  {
          printf("%s\n",h(f(1,2)));
          printf("%s\n",g(f(1,2)));
          return 0;
  }

Just by looking at the program one "might" expect the output to be, the same for both the printf statements. But on running the program you get it as:
bash$ ./a.out
12
f(1,2)
bash$

Why is it so?
这道题我也不明白,以后再做

第六道题:

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

If you expect the output of the above program to be NONE, I would request you to check it out!!
这道题需要细心观察,default在程序中被写成了defalut,而这在某些编译器是可以编译运行的(我在gcc,vc测过,是可以运行的),所以程序什么都不会输出.

第七道题:

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

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

Why does it happen so?
注意这个程序没有引入malloc函数原型所在的头文件,在IA-32平台下,因为没有指定头文件,编译器默认返回了一个32位的指针类型,在IA-64的情况下,因为没有指定头文件编译器还是返回的32位的,这样在转换的过程中将64位的截断成了32位,所以就出现段错误了.

第八道题:

Here is a small piece of program(again just 14 lines of program) which counts the number of bits set in a number.
Input 	Output
0 	0(0000000)
5 	2(0000101)
7 	3(0000111)

  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 =0, shift =1; i < 5; i ++, shift *= 2)
                  x = (x & mask[i ])+ ( ( x >> shift) & mask[i]);
          return x;
  }

Find out the logic used in the above program. 
位运算技巧的运用,以后再弄

第九道题:

What do you think would be the output of the following program and why? (If you are about to say "f is 1.0", I would say check it out again)

#include <stdio.h>

int main()
{
        float f=0.0f;
        int i;

        for(i=0;i<10;i++)
                f = f + 0.1f;

        if(f == 1.0f)
                printf("f is 1.0 \n");
        else
                printf("f is NOT 1.0\n");

        return 0;
}
浮点数加减法有很多让人意想不到的东西,特别是大数与小数相加时,所以出书f is NOT 1.0就是不足为奇了.

第十道题:

I thought the following C program is perfectly valid (after reading about the comma operator in C). But there is a mistake in the following program, can you identify it?

#include <stdio.h>

int main()
{
        int a = 1,2;
        printf("a : %d\n",a);
        return 0;
}
这里逗号的本意是将两个句子和在一块,少写分号.但是int a = 1做单个句子缺少分号;所以出现编译错误,要想避免编译错误有两种方法,第一种:将1,2用括号括起来,即a = (1,2);这时候a被初始化为2,或者int a; a = 1,2;此时a = 1.

第十一道题:

What would be the output of the following C program? (Is it a valid C program?)

#include <stdio.h>
int main()
{
        int i=43;
        printf("%d\n",printf("%d",printf("%d",i)));
        return 0;
}
printf函数的返回值是被打印的字符数,所以程序输出4321,另外这道题是ppurl.com注册时的一个题,很有点意思.

第十二道题:

 void duff(register char *to, register char *from, register int count)
  {
      register int n=(count+7)/8;
      switch(count%8){
      case 0: do{ *to++ = *from++;
      case 7:  *to++ = *from++;
      case 6: *to++ = *from++;
      case 5: *to++ = *from++;
      case 4: *to++ = *from++;
      case 3: *to++ = *from++;
      case 2: *to++ = *from++;
      case 1: *to++ = *from++;
              }while( --n >0);
      }
  }

Is the above valid C code? If so, what is it trying to acheive and why would anyone do something like the above? 
这段代码是合法的,在很多对性能要求苛刻的程序(如驱动程序中)有可能会用到,维基这篇文章阐述了这个东西,我表示自己也没理解透

第十三道题:

Here is yet another implementation of CountBits. Verify whether it is correct (how do you that???). If so, find out the logic used.

  int CountBits(unsigned int x)
  {
      int count=0;
      while(x)
      {
          count++;
          x = x&(x-1);
      }
      return count;
  }
位运算,x - 1将x二进制中最低位为1的进行借位,之后再&去除一个为1的位,这个方法也可以用来判断一个数是不是2的幂,有点意思

第十四道题:

Are the following two function prototypes same?

  int foobar(void);
  int foobar();

The following programs should be of some help in finding the answer: (Compile and run both the programs and see what happens)
Program 1:

  #include <stdio.h>
  void foobar1(void)
  {
   printf("In foobar1\n");
  }

  void foobar2()
  {
   printf("In foobar2\n");
  }

  int main()
  {
     char ch = 'a';
     foobar1();
     foobar2(33, ch);
     return 0;
  }

Program 2:

  #include <stdio.h>
  void foobar1(void)
  {
   printf("In foobar1\n");
  }

  void foobar2()
  {
   printf("In foobar2\n");
  }

  int main()
  {
     char ch = 'a';
     foobar1(33, ch);
     foobar2();
     return 0;
  }
首先这两个函数原型肯定是不一样的,第一个int foobar(void)表示函数不接受任何的参数,第二个int foobar()表示函数接受任意个数的参数,这说起来都是C语言的遗产了,K&R里面做了阐述,在C语言做标准化时引入了foobar(void)这样的void表示函数不接受任何参数,但是为了使得标准化之前的C代码还能够编译便保留了int foobar()这样的声明,且K&R建议在函数不需要参数的时候显式传入void,即第一种用法.上述程序中第一个程序能够编译通过,第二个则会报错.

第十五道题:

What's the output of the following program and why?

  #include <stdio.h>
  int main()
  {
   float a = 12.5;
   printf("%d\n", a);
   printf("%d\n", *(int *)&a);
   return 0;
  }
第二句printf将一个浮点数的二进制byte序列强制按一个int值来解读,所以会根据12.5在内存中的位序列将其解释为一个整数,或大或小.

第十六道题:

The following is a small C program split across files. What do you expect the output to be, when both of them compiled together and run?
File1.c

  int arr[80];

File2.c

  extern int *arr;
  int main()
  {
      arr[1] = 100;
      return 0;
  }
很经典的一道题,<C专家编程>上解释过

第十七道:

Explain the output of the following C program (No, the output is not 20).

  #include<stdio.h>
  int main()
  {
      int a=1;
      switch(a)
      {   int b=20;
          case 1: printf("b is %d\n",b);
                  break;
          default:printf("b is %d\n",b);
                  break;
      }
      return 0;
  }
作者给出了说明,输出肯定不是20,b输出的是一些随机的未初始化垃圾值,这是因为在switch中程序从default(如果没有case的话)或者case来开始执行,所以int b = 20;这一句没有执行,b是一些垃圾值.事实上在一些高级语言中,上述写法会报错,比如actionscript 3中上述写法就会报错"需要 CaseLabel".

第十八道:

What is the output of the following program? (Again, it is not 40, (if the size of integer is 4)).

  #define SIZE 10
  void size(int arr[SIZE])
  {
          printf("size of array is:%d\n",sizeof(arr));
  }

  int main()
  {
          int arr[SIZE];
          size(arr);
          return 0;
  }
犯了一个大错误,函数中不能传递数组的,只能通过指针和int arr[]这样的方式来传递,作者本意是给size函数传递一个10个元素的int型数组,但是arr[10]只是一个数,其含义在传递函数是与int* arr和int arr[]含义是不同的,不能这样用,另外需要注意的是sizeof(数组)只会返回整个数组所占字节的大小,而不是数组中元素的个数.

第十九道:

The following is a simple c program, in which there is a function called Error to display errors. Can you see a potential problem with the way Error is defined?

  #include <stdlib.h>
  #include <stdio.h>
  void Error(char* s)
  {
      printf(s);
      return;
  }

  int main()
  {
      int *p;
      p = malloc(sizeof(int));
      if(p == NULL)
      {
          Error("Could not allocate the memory\n");
          Error("Quitting....\n");
          exit(1);
      }
      else
      {
          /*some stuff to use p*/
      }
      return 0;
  }
挑不出啥大毛病,以后看

第二十道题:

What is the differnce between the following function calls to scanf?(Please notice the space carefully in the second call. Try removing it and observe the behaviour of the program)

  #include <stdio.h>
  int main()
  {
      char c;
      scanf("%c",&c);
      printf("%c\n",c);

      scanf(" %c",&c);
      printf("%c\n",c);

      return 0;
  }
不晓得,以后看

第二十一道:

What is the potential problem with the following C program?

  #include <stdio.h>
  int main()
  {
      char str[80];
      printf("Enter the string:");
      scanf("%s",str);
      printf("You entered:%s\n",str);

      return 0;
  }

字符串结尾问题,如果输入的过长,超过了80个字符,则str字符数组最后一个元素就不是\0,printf函数在打印时则会造成程序的越界访问甚至会崩溃.

第二十二道:

What is the output of the following program?

  #include <stdio.h>
  int main()
  {
      int i;
      i = 10;
      printf("i : %d\n",i);
      printf("sizeof(i++) is: %d\n",sizeof(i++));
      printf("i : %d\n",i);
      return 0;
  }
这个简单,sizeof操作符不会对其中传入的表达式或者函数等等求值,所以程序在32位机器输出10,4,10

第二十三道:

Why does the following program give a warning? (Please remember that sending a normal pointer to a function requiring const pointer does not give any warning)

  #include <stdio.h>
  void foo(const char **p) { }
  int main(int argc, char **argv)
  {
          foo(argv);
          return 0;
  }
以后解决

第二十四道:

What is the output of the following program?

  #include <stdio.h>
  int main()
  {
          int i;
          i = 1,2,3;
          printf("i:%d\n",i);
          return 0;
  }
这个和之前有关逗号的题一样,实际上是i = 1;2;3;这三句,所以会输出1.

第二十五道:

The following is a piece of code which implements the reverse Polish Calculator. There is a(are) serious(s) bug in the code. Find it(them) out!!! Assume that the function getop returns the appropriate return values for operands, opcodes, EOF etc..

  #include <stdio.h>
  #include <stdlib.h>

  #define MAX 80
  #define NUMBER '0'

  int getop(char[]);
  void push(double);
  double pop(void);
  int main()
  {
      int type;
      char s[MAX];

      while((type = getop(s)) != EOF)
      {
          switch(type)
          {
              case NUMBER:
                  push(atof(s));
                  break;
              case '+':
                  push(pop() + pop());
                  break;
              case '*':
                  push(pop() * pop());
                  break;
              case '-':
                  push(pop() - pop());
                  break;
              case '/':
                  push(pop() / pop());
                  break;
              /*   ... 
               *   ...    
               *   ... 
               */
          }
      }
  }
不会,以后弄

第二十六道:

The following is a simple program which implements a minimal version of banner command available on most *nix systems. Find out the logic used in the program.

  #include<stdio.h>
  #include<ctype.h>

  char t[]={
      0,0,0,0,0,0,12,18,33,63,
      33,33,62,32,62,33,33,62,30,33,
      32,32,33,30,62,33,33,33,33,62,
      63,32,62,32,32,63,63,32,62,32,
      32,32,30,33,32,39,33,30,33,33,
      63,33,33,33,4,4,4,4,4,4,
      1,1,1,1,33,30,33,34,60,36,
      34,33,32,32,32,32,32,63,33,51,
      45,33,33,33,33,49,41,37,35,33,
      30,33,33,33,33,30,62,33,33,62,
      32,32,30,33,33,37,34,29,62,33,
      33,62,34,33,30,32,30,1,33,30,
      31,4,4,4,4,4,33,33,33,33,
      33,30,33,33,33,33,18,12,33,33,
      33,45,51,33,33,18,12,12,18,33,
      17,10,4,4,4,4,63,2,4,8,
      16,63
      };

  int main(int argc,char** argv)
  {

      int r,pr;
      for(r=0;r<6;++r)
          {
          char *p=argv[1];

          while(pr&&*p)
              {
              int o=(toupper(*p++)-'A')*6+6+r;
              o=(o<0||o>=sizeof(t))?0:o;
              for(pr=5;pr>=-1;--pr)
                  {
                  printf("%c",( ( (pr>=0) && (t[o]&(1<<pr)))?'#':' '));

                  }
              }
          printf("\n");
          }
      return 0;
  }

不会,以后弄

第二十七道:

What is the output of the following program?

  #include <stdio.h>
  #include <stdlib.h>

  #define SIZEOF(arr) (sizeof(arr)/sizeof(arr[0]))

  #define PrintInt(expr) printf("%s:%d\n",#expr,(expr))
  int main()
  {
      /* The powers of 10 */
      int pot[] = {
          0001,
          0010,
          0100,
          1000
      };
      int i;

      for(i=0;i<SIZEOF(pot);i++)
          PrintInt(pot[i]);
      return 0;
  }
C语言中数字以0开头的话表示的是八进制的计数,所以上面数组中的前三项化为十进制为1,8,64,背离了程序作者的真实意思,在八进制时数字钟不能出现8,9这两个数

第二十八道:

The following is the implementation of the Euclid's algorithm for finding the G.C.D(Greatest Common divisor) of two integers. Explain the logic for the below implementation and think of any possible improvements on the current implementation.
BTW, what does scanf function return?

  #include <stdio.h>
  int gcd(int u,int v)
  {
      int t;
      while(v > 0)
      {
          if(u > v)
          {
              t = u;
              u = v;
              v = t;
          }
          v = v-u;
      }
      return u;
  }

  int main()
  {
      int x,y;
      printf("Enter x y to find their gcd:");
      while(scanf("%d%d",&x, &y) != EOF)
      {
          if(x >0 && y>0)
              printf("%d %d %d\n",x,y,gcd(x,y));
                  printf("Enter x y to find their gcd:");
      }
      printf("\n");
      return 0;
  }

Also implement a C function similar to the above to find the GCD of 4 integers.
表示不会,以后弄

第二十九道:

What's the output of the following program. (No, it's not 10!!!)

  #include <stdio.h>
  #define PrintInt(expr) printf("%s : %d\n",#expr,(expr))
  int main()
  {
      int y = 100;
      int *p;
      p = malloc(sizeof(int));
      *p = 10;
      y = y/*p; /*dividing y by *p */;
      PrintInt(y);
      return 0;
  }
/*与语句最后面的*/构成了注释符号,所以y = y/*p这句实际上成了y = y;所以程序会输出y:100.要想避免这样的情况很简单,用括号就行了即y = y/(*p);或者唉/*之间打个空格就够了此时程序就变成了y = y/ *p;这样就不会与后面的构成注释了.

第三十道:

The following is a simple C program to read a date and print the date. Run it and explain the behaviour

  #include <stdio.h>
  int main()
  {
      int day,month,year;
      printf("Enter the date (dd-mm-yyyy) format including -'s:");
      scanf("%d-%d-%d",&day,&month,&year);
      printf("The date you have entered is %d-%d-%d\n",day,month,year);
      return 0;
  }
以后看

第三十一道:

The following is a simple C program to read and print an integer. But it is not working properly. What is(are) the mistake(s)?

  #include <stdio.h>
  int main()
  {
      int n;
      printf("Enter a number:\n");
      scanf("%d\n",n);

      printf("You entered %d \n",n);
      return 0;
  }

首先scanf中n是不对的,应该传入&n,此外scanf("%d\n",n)中的\n也是问题,scanf中尽量不要使用非输入控制符,像上面的程序就需要输入两个数字程序才能运行完毕.此外,这个程序估计还有别的我不知道的问题.

第三十二道:

The following is a simple C program which tries to multiply an integer by 5 using the bitwise operations. But it doesn't do so. Explain the reason for the wrong behaviour of the program.

  #include <stdio.h>
  #define PrintInt(expr) printf("%s : %d\n",#expr,(expr))
  int FiveTimes(int a)
  {
      int t;
      t = a<<2 + a;
      return t;
  }

  int main()
  {
      int a = 1, b = 2,c = 3;
      PrintInt(FiveTimes(a));
      PrintInt(FiveTimes(b));
      PrintInt(FiveTimes(c));
      return 0;
  }
运算符优先级的问题,t = a << 2 + a,实际上等于t = a << (2 + a),所以出现了与程序作者原意不相符的情况.

第三十三道:

Is the following a valid C program?

  #include <stdio.h>
  #define PrintInt(expr) printf("%s : %d\n",#expr,(expr))
  int max(int x, int y)
  {
      (x > y) ? return x : return y;
  }

  int main()
  {
      int a = 10, b = 20;
      PrintInt(a);
      PrintInt(b);
      PrintInt(max(a,b));
  }
不是合法的C程序,在gcc下报错error: expected expression before 'return'

第三十四道:

The following is a piece of C code, whose intention was to print a minus sign 20 times. But you can notice that, it doesn't work.

  #include <stdio.h>
  int main()
  {
      int i;
      int n = 20;
      for( i = 0; i < n; i-- )
          printf("-");
      return 0;
  }

Well fixing the above code is straight-forward. To make the problem interesting, you have to fix the above code, by changing exactly one character. There are three known solutions. See if you can get all those three.
作者要求只改动一个字符使上述程序正常运行,暂时没有方法,以后弄.

第三十五道:

What's the mistake in the following code?

  #include <stdio.h>
  int main()
  {
      int* ptr1,ptr2;
      ptr1 = malloc(sizeof(int));
      ptr2 = ptr1;
      *ptr2 = 10;
      return 0;
  }
初始化的问题,只有ptr1被生命为一个int指针,ptr2其实被声明为一个int类型,这是问题所在,修改为int *ptr1,*ptr2;即可

第三十六道:

What is the output of the following program?

  #include <stdio.h>
  int main()
  {
      int cnt = 5, a;

      do {
          a /= cnt;
      } while (cnt --);

      printf ("%d\n", a);
      return 0;
  }

当cnt为1时while(cnt--)为真,所以继续进行循环,而此时cnt经过自减操作cnt为0,所以a /= cnt成了a /= 0,会发生除零错误

第三十七道题:

What is the output of the following program?

  #include <stdio.h>
  int main()
  {
      int i = 6;
      if( ((++i < 7) && ( i++/6)) || (++i <= 9))
          ;
      printf("%d\n",i);
      return 0;
  }
输出8,这个是逻辑运算符中的短路原则使用.

第三十八道题:

What is the bug in the following program?

  #include <stdlib.h>
  #include <stdio.h>
  #define SIZE 15 
  int main()
  {
      int *a, i;

      a = malloc(SIZE*sizeof(int));

      for (i=0; i<SIZE; i++)
          *(a + i) = i * i;
      for (i=0; i<SIZE; i++)
          printf("%d\n", *a++);
      free(a);
      return 0;
  }
这里第二个for循环中printf("%d\n",*a++),修改了分配内存后a的值,造成了后面free(a)内存释放不成功,造成内存泄露.

第三十九道题:

Is the following a valid C program? If so, what is the output of it?

  #include <stdio.h>
  int main()
  {
    int a=3, b = 5;

    printf(&a["Ya!Hello! how is this? %s\n"], &b["junk/super"]);
    printf(&a["WHAT%c%c%c  %c%c  %c !\n"], 1["this"],
       2["beauty"],0["tool"],0["is"],3["sensitive"],4["CCCCCC"]);
    return 0;
  }
不懂,以后弄

第四十道题:

What is the output of the following, if the input provided is:
Life is beautiful

  #include <stdio.h>
  int main()
  {
      char dummy[80];
      printf("Enter a string:\n");
      scanf("%[^a]",dummy);
      printf("%s\n",dummy);
      return 0;
  }
不懂,以后弄

第四十一道题:

 Note : This question has more to do with Linker than C language
We have three files a.c, b.c and main.c respectively as follows:
a.c
---

int a;

b.c
---

int a = 10;

main.c
------

extern int a;
int main()
{
        printf("a = %d\n",a);
        return 0;
}

Let's see what happens, when the files are compiled together:

bash$ gcc a.c b.c main.c
bash$ ./a.out
a = 10

Hmm!! no compilation/linker error!!! Why is it so?? 
不懂,以后弄

第四十二道题:

The following is the offset macros which is used many a times. Figure out what is it trying to do and what is the advantage of using it.

  #define offsetof(a,b) ((int)(&(((a*)(0))->b)))

这是stddef.h里定义的一个宏,其返回值为size_t,它适用于结构和union,用于检索结构成员相对于父结构的偏移量,第一个参数为结构名称,第二个参数为结构中的字段名,其主要实现如下:将地址0强制转换为对应结构指针,此时结构的地址为0,然后使用->获得b的内容,再使用&操作符获得b的地址,再将b的地址转换为int类型,使用b的地址减去结构地址0(因为是0强转的),即为结构字段b相对于结构的偏移量,这种在嵌入式里面用的比较多,这里有一篇详解它的文章.它的使用例子如下:

#include <stdio.h>
#include <stddef.h>

void main(void)
{	
	struct test
	{
		int a;
		short b;
		char c;
		int d;
	};
	struct test a;
	size_t offset = offsetof(struct test,c);
	printf("the offset of c is %d\n",offset);	/* 输出6,因为32位机器上int占4字节,short为2字节	*/
}

第四十三道题:

The following is the macro implementation of the famous, Triple xor swap.

  #define SWAP(a,b) ((a) ^= (b) ^= (a) ^= (b))

What are the potential problems with the above macro? 
没有十足把握,不要乱用宏,首先扩展的问题,上面的宏SWAP(1,2)运行正常,SWAP(a++,b++)就会报错,SWAP(1 + 2,2 + 3)同样报错,那SWAP(SWAP(1+2),SWAP(2+3))更加报错,此外有可能还有我没发现的错误,所以还是那句话不是大牛,用宏一定要当心,宏也是会耍大牌的.

第四十四道题:

What is the use of the following macro?

  #define DPRINTF(x) printf("%s:%d\n",#x,x)
宏中#的用法,很常见

第四十五道题:

Let's say you were asked to code a function IAddOverFlow which takes three parameters, pointer to an integer where the result is to be stored, and the two integers which needs to be added. It returns 0 if there is an overflow and 1 otherwise:

  int IAddOverFlow(int* result,int a,int b)
  {
      /* ... */
  }

So, how do you code the above function? (To put in a nutshell, what is the logic you use for overflow detection?) 
不懂,以后弄

第四十六道题:

What does the following macro do?

  #define ROUNDUP(x,n) ((x+n-1)&(~(n-1)))
不懂,以后弄

第四十七道题:

Most of the C programming books, give the following example for the definition of macros.

  #define isupper(c) (((c) >= 'A') && ((c) <= 'Z'))

But there would be a serious problem with the above definition of macro, if it is used as follows (what is the problem??)

  char c;
  /* ... */
  if(isupper(c++))
  {
      /* ... */
  }

But most of the libraries implement the isupper (declared in ctypes.h) as a macro (without any side effects). Find out how isupper() is implemented on your system. 

如果调用issuper(c++),那么实际上c++在宏中调用了两次,比如c = 'Y',调用issuper(c++)完后Y就变成了字符[,与作者本意不同,因为作者本意是c++运算后,此时运算为字符'Z',一般机器上的都是用位运算来做的,因为大小写字母刚好差32,换算成十六进制就是0x20,即大小写字母只是在第六位(从右到左数)比特位上不相同,其他比特字节相同,所以用位运算又快又准确.

第四十八道题:

I hope you know that ellipsis (...) is used to specify variable number of arguments to a function. (What is the function prototype declaration for printf?) What is wrong with the following delcaration?

  int VarArguments(...)
  {
      /*....*/
      return 0;
  }
不懂,以后弄

第四十九道题:

Write a C program to find the smallest of three integers, without using any of the comparision operators. 

我的思路,使用位运算

#include <stdio.h>

/**
 * 找到两个数中的较小的数,如果相等返回同一个数
 * 这种方法只适用于使用补码表示有符号数的计算机,且是8比特补码系统
 */
int findLess(int a,int b)
{
	int c = a - b;
	int flag = c >> (sizeof(int) * 8 - 1);	/* 获取标志位 */
	if(flag)	/* 标志位为1表示结果为负数 */
	{
		return a;
	}
	else if(c)	/* 此时标志位为0,表示c为非负数,如果c为真,表示c大于0,返回b */
	{
		return b;
	}
	else		/* c为0,表示两个数相等 */
	{
		return a;
	}
	printf("compare error\n");
	return -1;
}

void main(void)
{
	int a = 1,b = 2,c = 2;
	
	printf("the small integer is %d\n",findLess(a,findLess(b,c)));
}

第五十道题:

What does the format specifier %n of printf function do?

msdn描述如下,%n表示当前已经成功写入流或者缓冲的字符数目;该值保存在一个整数中,其地址作为参数传给printf函数,且说明%n内在并不安全,所以默认情况下是禁用的,要使用%n,请查看_set_printf_count_output等.例子如下:

#include <stdio.h>

/**
 * gcc编译
 */
void main(void)
{
	char* str = "hello world";
	int n;
	printf("%s\n%n",str,&n);	/* 传入n的地址 */
	printf("%d\n",n);			/* 打印n的值 */
}

第五十一道题:

Write a C function which does the addition of two integers without using the '+' operator. You can use only the bitwise operators.(Remember the good old method of implementing the full-adder circuit using the or, and, xor gates....) 
不懂,以后弄

第五十二道题:

How do you print I can print % using the printf function? (Remember % is used as a format specifier!!!) 

#include <stdio.h>

void main(void)
{
	printf("I can print %% use the printf function\n");
}

第五十三道题:

What's the difference between the following two C statements?

  const char *p;
  char* const p;
含义不同,第一个表示的是p指向一个常量char或者非常量char,p在初始化为指向一个常量char之后还可以改变为指向别的char(常量或者非常量都可),也可使用*p作为只读的数据,但是不能使用*p来修改其所指向的char的值,即不允许你*p = 'a';之类的句子出现,示例程序如下:

#include <stdio.h>

int main()
{
	const char a = 'a';
	const char b = 'b';
	char c = 'c';
	
	const char *p;
	
	p = &a;
	printf("%c\n",*p);	/* 输出a */
	p = &b;
	printf("%c\n",*p);	/* 输出b */
	p = &c;
	printf("%c\n",*p);	/* 输出c */
	
	/*
		*p = 'd';	这句需要注释掉,否则会报错error: assignment of read-only location '*p'
	*/
	return 0;
}
char * const p;表示的是该定义的该指针变量是一个常量,所以p在定义时必须赋值(也可以不赋值,这时候其中是编译器给其分配的随机数值,但我们之后不能再对其赋值,所以如果不赋值的话这个变量没有用),因为常量在第一次赋值后不允许再次赋值,p指向的数据可以被修改,p自己本身的值不能被修改,示意程序如下:

#include <stdio.h>

int main()
{
	const char a = 'a';
	char b = 'b';
	char c = 'c';
	
	/*
		这句注释掉,否则会报warning: initialization discards 'const' qualifier from pointer target type [enabled by default]
		这也说明不要将常量的地址赋值给char* const 类型的指针
		char* const p = &a;
	*/
	
	char* const p = &b;	/* 定义时即赋值 */
	printf("%c\n",*p);
	
	*p = c;				/* 可以使用p修改p所指向的数据 */
	printf("%c\n",b);
	printf("%c\n",c);
	
	/*
		p = &c;		这句需要注释掉,否则报错error: assignment of read-only location '*p'
	*/
}

第五十四道题:

What is the difference between memcpy and memmove? 

如果传入的原地址与目标地址有重叠的话,memmove总能正确处理,memcpy则不一定可行.

第五十五道题:

What is the format specifiers for printf to print double and float values? 
以后查

第五十六道题:

Write a small C program to determine whether a machine's type is little-endian or big-endian.
这个比较简单,两种方法,一种使用指针,一种使用union,示例程序如下:

方法一:
#include <stdio.h>

int main(void)
{
	int a = 1;
	char *p = (char*) &a;
	
	if(*p == 1)
	{
		printf("the machine is little endian\n");
	}
	else
	{
		printf("the machine is big endian\n");
	}
	
	return 0;
}

方法二:
#include <stdio.h>

typedef union endian_
{
	int a;
	char b;
} Endian;

int main(void)
{
	Endian a;
	a.a = 1;
	if(a.b == 1)
	{
		printf("the machine is little endian\n");
	}
	else
	{
		printf("the machine is big endian\n");
	}
	return 0;
}
第五十七道题:

Write a C program which prints Hello World! without using a semicolon!!! 

stackOverflow给输了多种答案,下面是其中的一种

#include <stdio.h>

void main(void)
{
	if(printf("hello world\n")){}
}

相关文章推荐

文明盛世饮料谜题c++源码

  • 2013年11月07日 11:22
  • 7KB
  • 下载

算法谜题.pdf

  • 2017年04月19日 21:05
  • 33.57MB
  • 下载

[NOIP2016] 玩具谜题

模拟

谜题8:Dos Equis

这个谜题将测试你对条件操作符的掌握程度,这个操作符有一个更广为人知的名字:问号冒号操作符。下面的程序将会打印出什么呢? public class DosEquis{ public static v...

《算法谜题》

  • 2016年05月01日 13:18
  • 12.21MB
  • 下载

谜题5:十六进制的趣事

下面的程序是对两个十六进制(hex)字面常量进行相加,然后打印出十六进制的结果。这个程序会打印出什么呢? public class JoyOfHex{ public static void mai...

算法谜题,完整清晰版

  • 2016年11月27日 15:25
  • 30.71MB
  • 下载
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:C谜题解释
举报原因:
原因补充:

(最多只允许输入30个字)