【发布时间】:2018-11-05 20:04:49
【问题描述】:
我在一本书中阅读了这个示例代码。我不明白为什么以下示例代码的函数声明的这一部分是必要的:
while (i <= n)
p[i++] = '\0'; // set rest of string to '\0'
这是整个代码:
#include <iostream>
const int ArSize = 80;
char * left(const char * str, int n = 1);
int main()
{
using namespace std;
char sample[ArSize];
cout << "Enter a string:\n";
cin.get(sample,ArSize);
char *ps = left(sample, 4);
cout << ps << endl;
delete [] ps; // free old string
ps = left(sample);
cout << ps << endl;
delete [] ps; // free new string
return 0;
}
// This function returns a pointer to a new string
// consisting of the first n characters in the str string.
char * left(const char * str, int n)
{
if(n < 0)
n = 0;
char * p = new char[n+1];
int i;
for (i = 0; i < n && str[i]; i++)
p[i] = str[i]; // copy characters
while (i <= n)
p[i++] = '\0'; // set rest of string to '\0'
return p;
}
我擦掉后运行代码,没有问题。
【问题讨论】:
-
不需要循环,但如果要将
p视为以空字符结尾的字节字符串,则需要p[i++] = '\0'。 -
另外,请学习如何缩进你的代码。它很可能在书中缩进了,虽然编译器不需要缩进,但它确实有助于人们阅读代码。
-
而且 while 循环没有嵌套在 for 循环内 - 在 for 语句的关闭之后没有立即打开大括号,因此它只循环
p[i] = str[i];这种混乱/缺乏清晰度是一些编码标准要求所有 for/while/if/else 语句后跟 {} -
你可以用
p[i] = '\0';替换它,一个终止的null就足够了 -
while 循环很可笑。在
for循环之后需要p[i] = 0;来正确终止字符串。如果输入字符串str的长度小于n,则为p分配的内存量也过多。这是哪本书?
标签: c++ for-loop while-loop