C Primer Plus 11.12 复习题

1、

答:字符串是以空字符('\0')结尾的一系列字符,故上述声明的是一个字符数组,不是字符串。

2、

3、

4、

5、

a.

b.

指向 char 类型的指针

c.

字符串 "Ho Ho Ho!" 的首地址。

d.

*--pc : 表示指针先前移动一位,然后取指针指向的值。

--*pc : 先取指针指向的值,然后值减1.

e.

f.

第 1 个 while 循环用来测试是否到达字符串末尾的空字符('\0') ;

第 2 个 do{}while 循环用来测试是否到达该字符串的首字符.

g.

由于 *pc 为空字符('\0'),不会进入第 1 个 while 循环,第二个 do{}while 循环先对 pc 递减,则表达式 pc - str 永远为负,循环一直进行下去。

h.

主调函数需调用pr()前要声明函数 char *pr(char *str);

主调函数需要声明指针 char 类型变量 x,即 char *x 。

6、

sign 是 char 类型变量,占 1 个字节的内存。

'$' 是 char 字面值常量,占 1 个字节的内存。

"$" 是字符串字面值,末尾还有空字符('\0'),占 2 个字节的内存。

7、

8、

9、

复制代码
char *s_gets(char *st, int n)
{
	
	char *ret_val;
	
	char *ptr;
	
	ret_val = fgets(st, n, stdin);
	
	if(ret_val)
	{
		
		ptr = st;
			
		while(*ptr != '\n' && *ptr != '\0')
			
			ptr++;
			
		if(*ptr == '\n')
		
			*ptr = '\0';
			
		else
		
			while(getchar() != '\n')
			
				continue;
						
	}
	
	return ret_val;
}

10、

复制代码
int strlen(char *st)
{
	int i = 0;
	
	while(*st++)
	
		i++;
	
	return i;
}

11、

复制代码
#include <string.h>  // 有 strchr() 函数

char *s_gets(char *st, int n)
{
	char *ret_val;
	
	char *find;

	ret_val = fgets(st, n, stdin);
	
	if (ret_val)
	{
		
		find = strchr(st, '\n');
		
		if (find)
			
			*find = '\0';
		
		else
			
			while (getchar() != '\n')
				
				continue;
	}
	
	return ret_val;
}	

12、

复制代码
#include <stdio.h>

char *find_first_space(const char *str)
{
 
    if (str == NULL)
        
		return NULL;
    
    while (*str != '\0') 
	{
        if (*str == ' ') 
	
          	return (char *)str;
        
        str++;
    }
    

    return NULL;
}


/*

括号 (char *) 是 C 语言类型转换操作符的固定语法格式。它告诉编译器:"将 str 从 const char * 类型转换为 char * 类型"。

*/

13、

复制代码
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define ANSWER "Grant"
#define SIZE 40

char *s_gets(char *st, int n);

void upper(char *str);

int main()
{
	char try[SIZE];

	puts("Who is buried in Grant's tomb?");
	
	s_gets(try, SIZE);
	
	upper(try);
	
	while(strcmp(try, ANSWER) != 0)
	{
		
		puts("No, that's wrong. Try again.");
		
		s_gets(try, SIZE);
		
		upper(try);
	
	}
	
	puts("That's right);

	return 0;
}

char *s_gets(char *st, int n)
{
	char *ret_val;
	
	char *find;

	ret_val = fgets(st, n, stdin);
	
	if (ret_val)
	{
		
		find = strchr(st, '\n');
		
		if(find)
		
			*find = '\0';
		
		else
		
			while(getchar() != '\n')
		
				continue;
	}
	
	return ret_val;
}

void upper(char *str)
{
	while(*str)
	{
		*str = toupper(*str);
		
		++str;
	}
}	
相关推荐
RuoZoe2 天前
重塑WPF辉煌?基于DirectX 12的现代.NET UI框架Jalium
c语言
祈安_5 天前
C语言内存函数
c语言·后端
郑州光合科技余经理7 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo1237 天前
matlab画图工具
开发语言·matlab
dustcell.7 天前
haproxy七层代理
java·开发语言·前端
norlan_jame7 天前
C-PHY与D-PHY差异
c语言·开发语言
多恩Stone7 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
QQ4022054967 天前
Python+django+vue3预制菜半成品配菜平台
开发语言·python·django
czy87874757 天前
除了结构体之外,C语言中还有哪些其他方式可以模拟C++的面向对象编程特性
c语言
遥遥江上月7 天前
Node.js + Stagehand + Python 部署
开发语言·python·node.js