为什么按值传递的指向 char 的指针找不到空终止符?
我已经盯着这个问题有一段时间了,我对 for
循环中发生的情况感到困惑。
首先,我让用户输入一个使用 cin.getline() 读取的短语,
const int STRING_MAX = 1001;
char* inputString = nullptr;
inputString = new char[STRING_MAX];
cin.getline(inputString, STRING_MAX, '\n');
以防有人想知道..我没有填充缓冲区(无论如何这都不重要) 。我只输入大约 25 个字符。
接下来 inputString
按值传递给 Palindrome 类
成员函数
word(char* source)
这就是我当前在函数中尝试做的所有事情:
bool Palindrome::word(char* source) {
for (char* iterator = source; iterator != '\0'; iterator++)
cout << *iterator << endl;
}
我实际上正在做更多的事情,但是在此刻,我将代码简化为您在上面看到的内容,并且出于某种我不明白的原因,循环超出了 char* 数组
有人可以帮助我理解发生了什么吗这里?
顺便说一句,对于这个作业,我很了解 C++ 中的字符串类(讲师希望我们使用指针以及 new 和 delete 运算符)。
I've been staring at this for a while now and I'm confused about what is happening in regards to my for
loop.
To start, I am having the user enter a phrase which is read using cin.getline()
const int STRING_MAX = 1001;
char* inputString = nullptr;
inputString = new char[STRING_MAX];
cin.getline(inputString, STRING_MAX, '\n');
In case anyone is wondering.. I'm not filling up the buffer (which shouldn't matter anyway). I'm only entering about 25 characters.
Next inputString
is passed by value to the Palindrome class
member function
word(char* source)
This is all I'm currently trying to do in the function:
bool Palindrome::word(char* source) {
for (char* iterator = source; iterator != '\0'; iterator++)
cout << *iterator << endl;
}
I'm actually doing more, but at the moment, I reduced the code to what you see above, and for some reason, which I do not understand, the loop runs past the bounds of the char* array
Can someone help me to understand what is happening here?
By the way, I am well aware of the string class in C++, however, for this assignment (the instructor wants us to use pointers and the new and delete operators).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
iterator != '\0'
这测试iterator
是否为空指针。情况永远不会是这样,这也不是您真正想要的。您的代码不正确,但恰好是有效代码,因为
'\0'
是整数值零的词法表示,因此它恰好是空指针持续的。要测试
iterator
是否指向空终止符,您需要使用*iterator != '\0'
(或者只测试*iterator
,因为整数值 0 的计算结果为 false)。iterator != '\0'
This tests whetheriterator
is a null pointer. This will never be the case and it is not what you really want.Your code is incorrect but just happens to be valid code because
'\0'
is a lexical representation of the integer value zero, and is thus it happens to be a null pointer constant.To test whether
iterator
points to a null terminator, you need to use*iterator != '\0'
(or just test*iterator
, since an integer value of zero evaluates to false).