c++ primer 3.5.4节练习答案

练习3.37

输出字符数组ca的值hello;疑问:此时的*cp作为循环的判断条件是否能够很好的终止循环,当cp指向尾后元素时,*cp不合法,但是系统不会报错,之后输出会出现什么未知,编译后验证疑问正确,在正确输出hello后仍输出了一段乱码字符。

练习3.38

指针是用来代表内存地址的。指针的数值是该地址相对于最低位地址也就是0位地址的偏移量,也可称之为坐标。坐标相加得到的新值是没什么意义的,坐标相减则是距离,坐标加距离则是新坐标,后两者是有意义的。

练习3.39

string对象

int main()
{
	string str1, str2;
	while (cin >> str1 >> str2)
	{
		if (str1 > str2)
			cout << "1" << endl;
		else if (str1 < str2)
			cout << "-1" << endl;
		else
			cout << "0" << endl;
	}
	system("pause");
	return 0;
}

C风格字符串

int main()
{
    const char ca[] = { 'h','e','l','l','o' };
    const char cb[] = { 'h','i' };
    cout << strcmp(ca, cb) << endl;
    system("pause");
    return 0;
}

练习3.40

 1 int main()
 2 {
 3     char ca[] = { 'h','e','l','l','o','\0' }; //在这里出现错误,刚开始没加终止符,导致程序一直出错,注意书上109页说的传入此类函数的指针必须指向以空字符作为结束的数组
 4     char cb[] = { 'w','o','r','\0' };
 5     char cc[10];
 6     strcpy_s(cc, ca);
 7     strcat_s(cc, " ");
 8     strcat_s(cc, cb);
 9     for (auto i : cc)
10         cout << i;
11     system("pause");
12     return 0;
13 }

 

posted @ 2017-07-27 17:32  五月份小姐  阅读(389)  评论(0)    收藏  举报