33-复习题
11.12 复习题
复习题的参考答案在附录A中。
1.下面字符串的声明有什么问题?
int main(void)
{
char name[] = {'F', 'e', 's', 's' };
...
}
2.下面的程序会打印什么?
#include <stdio.h>
int main(void)
{
char note[] = "See you at the snack bar.";
char *ptr;
ptr = note;
puts(ptr);
puts(++ptr);
note[7] = '\0';
puts(note);
puts(++ptr);
return 0;
}
3.下面的程序会打印什么?
#include <stdio.h>
#include <string.h>
int main(void)
{
char food [] = "Yummy";
char *ptr;
ptr = food + strlen(food);
while (--ptr >= food)
puts(ptr);
return 0;
}
4.下面的程序会打印什么?
#include <stdio.h>
#include <string.h>
int main(void)
{
char goldwyn[40] = "art of it all ";
char samuel[40] = "I read p";
const char * quote = "the way through.";
strcat(goldwyn, quote);
strcat(samuel, goldwyn);
puts(samuel);
return 0;
}
5.下面的练习涉及字符串、循环、指针和递增指针。首先,假设定义了下面的函数:
#include <stdio.h>
char *pr(char *str)
{
char *pc;
pc = str;
while (*pc)
putchar(*pc++);
do {
putchar(*--pc);
} while (pc - str);
return (pc);
}
考虑下面的函数调用:
x = pr("Ho Ho Ho!");
a.将打印什么?
b. x
是什么类型?
c. x
的值是什么?
d.表达式 --pc
是什么意思?与 --
pc
有何不同?
e.如果用 pc--
替换 --pc
,会打印什么?
f.两个 while
循环用来测试什么?
g.如果 pr()
函数的参数是空字符串,会怎样?
h.必须在主调函数中做什么,才能让 pr()
函数正常运行?
6.假设有如下声明:
char sign = '$';
sign
占用多少字节的内存? '$'
占用多少字节的内存? "$"
占用多少字节的内存?
7.下面的程序会打印出什么?
#include <stdio.h>
#include <string.h>
#define M1 "How are ya, sweetie? "
char M2[40] = "Beat the clock.";
char * M3 = "chat";
int main(void)
{
char words[80];
printf(M1);
puts(M1);
puts(M2);
puts(M2 + 1);
strcpy(words, M2);
strcat(words, " Win a toy.");
puts(words);
words[4] = '\0';
puts(words);
while (*M3)
puts(M3++);
puts(--M3);
puts(--M3);
M3 = M1;
puts(M3);
return 0;
}
8.下面的程序会打印出什么?
#include <stdio.h>
int main(void)
{
char str1 [] = "gawsie";
char str2 [] = "bletonism";
char *ps;
int i = 0;
for (ps = str1; *ps != '\0'; ps++) {
if (*ps == 'a' || *ps == 'e')
putchar(*ps);
else
(*ps)--;
putchar(*ps);
}
putchar('\n');
while (str2[i] != '\0') {
printf("%c", i % 3 ? str2[i] : '*');
++i;
}
return 0;
}
9.本章定义的 s_gets()
函数,用指针表示法代替数组表示法便可减少一个变量 i
。请改写该函数。
10. strlen()
函数接受一个指向字符串的指针作为参数,并返回该字符串的长度。请编写一个这样的函数。
11.本章定义的 s_gets()
函数,可以用 strchr()
函数代替其中的 while
循环来查找换行符。请改写该函数。
12.设计一个函数,接受一个指向字符串的指针,返回指向该字符串第 1
个空格字符的指针,或如果未找到空格字符,则返回空指针。
13.重写程序清单11.21,使用 ctype.h
头文件中的函数,以便无论用户选择大写还是小写,该程序都能正确识别答案。