C puzzles详解【21-25题】

第二十一题

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
",str);

      return 0;
  }
题目讲解:
易造成数组越界,scanf改成如下形式比较保险
scanf("%79s",str);
不管输入多少个字节,最多只读取79个字节。

第二十二题

What is the output of the following program? 
  #include <stdio.h>
  int main()
  {
      int i;
      i = 10;
      printf("i : %d
",i);
      printf("sizeof(i++) is: %d
",sizeof(i++));
      printf("i : %d
",i);
      return 0;
  }
题目讲解:
输出为:
i: 10
sizeof(i++) is:4
i: 10
sizeof(i++),等效于sizeof(int)。sizeof的值在编译时决定,不会执行i++。
sizeof的更多讲解见第一题。

第二十三题

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;
  }
题目讲解
  • 关键字const
用const修饰变量,指定该变量为只读。

const int a = 10;//变量a只读

const int *p;//p指向的int型数只读,p可以被修改

int *const p;//p为只读,p指向的int型数可以被修改
  • 带const的一级指针和二级指针赋值
int a = 10;

const int *p;

p = &a;//一级const指针赋值时,可以不将右边的指针转换为const型
int *p;

const int **pp;

pp = (const int **)&p;//二级const指针赋值时,必须将右侧二级指针转换为const型
  • 带const的一级指针和二级指针传参
void foo(const char *p) {}
int main()
{
char *p;
foo(p);//p不用转化为const型
return 0;
}
void foo(const char **pp) {}
int main()
{
char **pp;
foo((const char **)pp);//pp必须转化为const型
return 0;
}

第二十四题

What is the output of the following program? 
  #include <stdio.h>
  int main()
  {
          int i;
          i = 1,2,3;
          printf("i:%d
",i);
          return 0;
  }
题目讲解:
同第十题。
输出: i:1
逗号运算符在所有的运算符中优先级最低,i = 1,2,3等效于(i = 1),2,3
若将”i = 1,2,3”改成”i = (1,2,3)”,i的值为3。


第二十五题(Reverse Polish Notation)

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;
              /*   ... 
               *   ...    
               *   ... 
               */
          }
      }
  }
题目讲解:(不确定)
减法的减数和被减数反了,除法的除数和被除数反了。
原文地址:https://www.cnblogs.com/tanghuimin0713/p/3987533.html