【发布时间】:2012-07-12 09:47:28
【问题描述】:
我正在测试“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++ 编译器。
【问题讨论】:
-
不要使用
char数组,使用std::string。 -
该技巧称为缓冲区溢出,在许多情况下被认为是具有安全隐患的漏洞。并非每次缓冲区溢出都会导致崩溃或立即导致崩溃。
-
行为未定义,正如其他人所说。不过,额外的字符很有可能会进入
name2。您可以尝试打印。 -
这就是为什么程序员应该学习汇编语言的基础知识:在调试器中单步执行这段代码不仅可以回答他的问题,还可以填补他理解中的其他(明显的)空白。
-
这就是为什么 C++ 程序员应该总是更喜欢使用像字符串和向量这样的对象而不是固定大小的数组。有时您确实需要一个数组来与系统调用或其他库进行交互,但这些是例外。
标签: c++ arrays string char strlen