C++ 动态分配的字符串数组,然后更改它的值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20207400/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Dynamically allocated string array, then change it's value?
提问by PeppeJ
I'm trying to create a string array and use a pointer to modify it. I'm not sure how to declare the pointer since strings can vary in length, and I think this is what causes the error.
我正在尝试创建一个字符串数组并使用指针来修改它。我不确定如何声明指针,因为字符串的长度可能会有所不同,我认为这就是导致错误的原因。
My code looks something like this:
我的代码看起来像这样:
#includes <string>
#includes <iostream>
using namespace std;
string *users = NULL;
int seatNum = NULL;
cin >> seatNum;
users = new string[seatNum];
string name;
cin >> name;
users[seatNum] = name;
It throws me an Write Access Violation when I try to change its value. From what I've read it's because strings are compiled as read-only, so my question is how would I/what would I do to change it? Easy-to-understand explanations would be preferable.
当我尝试更改其值时,它会引发写入访问冲突。从我读过的内容来看,这是因为字符串被编译为只读,所以我的问题是我/我将如何更改它?通俗易懂的解释会更可取。
回答by bvj
You're accessing memory beyond the range of the allocated array
您正在访问超出分配数组范围的内存
users = new string[seatNum];
users[seatNum] = name;
The first element is [0]. The last is [seatNum-1]
第一个元素是 [0]。最后一个是 [seatNum-1]
回答by Shoe
You have created an array of seatNum
elements. Array element indexing starts at 0
therefore the range of valid indexes is [0, seatNum - 1]
. By accessing users[seatNum] = ...
you are effectively going past the last valid element of the array. This invokes UB (undefined behavior).
您已经创建了一个seatNum
元素数组。数组元素索引开始于,0
因此有效索引的范围是[0, seatNum - 1]
。通过访问,users[seatNum] = ...
您可以有效地通过数组的最后一个有效元素。这将调用 UB(未定义行为)。
I see you have already made the right choice of using std::string
instead of C-style strings. Why not make the same choice over arrays?
我看到您已经做出了正确的选择,使用std::string
而不是 C 风格的字符串。为什么不在数组上做出同样的选择?
#include <string>
#include <array>
#include <iostream>
int main(int, char*[]) {
int seatNum = 0;
std::cin >> seatNum;
std::vector<std::string> users(seatNum);
std::cin >> users[0];
return 0;
}
Try to avoid pointers and C-style arrays, especially dynamic ones.
尽量避免使用指针和 C 风格的数组,尤其是动态数组。
回答by Pepe
A few things:
一些东西:
int seatNum will be allocated on the stack and will never be NULL. You should set it to 0.
You are setting users[seatNum] which is out of bounds causing your program to crash. You can only use indices from 0 to seatNum-1.
int SeatNum 将在堆栈上分配并且永远不会为 NULL。您应该将其设置为 0。
您正在设置 users[seatNum] 超出范围导致您的程序崩溃。您只能使用从 0 到 SeatNum-1 的索引。
Updated: Chris is correct. I looked into it and strings are indeed mutable in C++.
更新:克里斯是正确的。我查看了它,字符串在 C++ 中确实是可变的。