我正在测试“C++ Premiere”一书中关于 C++ 字符串的示例。
const int size = 9;
char name1[size];
char name2[size] = "C++owboy"; // 8 characters here
cout << "Howdy! I'm " << name2 << "! What's your name?" << endl;
cin >> name1; // I input "Qwertyuiop" - 11 chars. It is more than the size of name1 array;
// now I do cout
cout << "Well, your name has " << strlen(name1) << " letters"; // "Your name has 11 letters".
cout << " and is stored in an array of " << size(name1) << " bytes"; // ...stored in an array of 9 bytes.
为什么 11 个字符存储在数组中只是为了 8 个字符 + '\0' 个字符?它在编译时变宽了吗?或者字符串存储在其他地方?
此外,我不能:
const int size = 9;
char name2[size] = "C++owboy_12345"; // assign 14 characters to 9 chars array
但可以做我上面写的:
cin >> name1; // any length string into an array of smaller size
这里有什么技巧?我使用 NetBeans 和 Cygwin g++ 编译器。
最佳答案
将比数组大小更多的条目写入数组允许调用未定义的行为。计算机可能将该数据存储在任何地方,或者根本不存储。
通常,数据存储在内存中的下一个位置。这可能是另一个变量、指令流,甚至是您椅子下面的炸弹的控制寄存器。
简单地说:您编写了一个缓冲区溢出错误。不要那样做。
只是为了好玩:未定义的行为 是 C++ 标准没有注释的行为。它可以是任何东西,因为标准对其没有任何限制。
在一个特定案例中,该行为使我的银行余额从 10 美元增加到 18 亿美元:http://ideone.com/35FQW
您能看出为什么该程序可能会这样吗?
关于c++ - 如果存储字符串的 char 数组小于字符串,那么 C++ 真正存储字符串的位置是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11455302/