[英]Array assignment not working with pointer syntax
#include <iostream>
int main() {
char* chars = new char[4];
for(int i = 0; i < 4; ++i)
{
chars[i] = 'a';
}
std::cout << chars;
return 0;
}
That chunk of code works correctly. 那段代码正常工作。 stdout says
标准输出说
aaaa
However, changing 但是,改变
chars[i] = 'a';
to 至
*chars++ = 'a';
or 要么
*(chars++) = 'a';
make stdout empty with nothing in stderr. 使stdout为空,stderr中没有任何内容。 What's going on?
这是怎么回事? I thought the [] was just syntactic sugar for *pointer.
我以为[]只是* pointer的语法糖。
The problem is that by iterating through chars
using *chars++ = 'a'
you modify the pointer. 问题在于,通过使用
*chars++ = 'a'
遍历chars
可以修改指针。 When you finally output the string, it is pointing to the character just past the end of the string. 当您最终输出字符串时,它指向的是字符串末尾的字符。
Perhaps you were trying to do something like this: 也许您正在尝试执行以下操作:
for( char *p = chars, *end = chars + 4; p != end; )
{
*p++ = 'a';
}
But this is ugly. 但这是丑陋的。 The first way (
chars[i]
) was better. 第一种方法(
chars[i]
)更好。 In either case, your array is not large enough to hold a 4-character string because you need a null-terminator. 无论哪种情况,您的数组都不足以容纳4个字符的字符串,因为您需要一个空终止符。
char *chars = new char[5];
char *p = chars;
for( int i = 0; i < 4; i++ ) *p++ = 'a';
*p = '\0'; // null-terminate the string
cout << chars;
delete [] chars;
Note that there's not much use in dynamic allocation in your case. 请注意,在这种情况下,动态分配没有太大用处。 Why not just declare chars on the stack?
为什么不只在堆栈上声明char? Also, initialising it with all zeroes is not a bad practice:
同样,用全零初始化不是一个坏习惯:
char chars[5] = {0};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.