gpt4 book ai didi

c++ - strcat访问冲突写位置c++

转载 作者:行者123 更新时间:2023-11-30 02:40:16 25 4
gpt4 key购买 nike

我读到一个错误:

Unhandled exception at 0x5AAF40D9 (msvcr120d.dll) in Homework6_10_7.exe: >0xC0000005: Access violation writing location 0x006A0000.

运行这段代码时:

int main()
{
//variables
const int SIZE = 30;
char first[SIZE];
char middle[SIZE];
char last[SIZE];
char full[100];
const char comma[2] = { ',', '\0'};
const char space[2] = { ' ', '\0' };
int length = 0;

//Get the user names
cout << "Enter your first name: ";
cin.getline(first, 30);

cout << "Enter your middle name: ";
cin.getline(middle, 30);

cout << "Enter your last name: ";
cin.getline(last, 30);

//Puts the given name values into the full desired format,
strcat(full, last);
strcat(full, comma);
strcat(full, space);
strcat(full, first);
strcat(full, space);
strcat(full, middle);

//outputs the full name array.
cout << "Welcome new user " << full << endl;

system("PAUSE");

return 0;
}

有什么我想念的吗? strcat 似乎是导致问题的原因,但我不确定为什么。感谢任何帮助,谢谢。

最佳答案

strcat 将源字符串的拷贝附加到目标字符串。 destination 中的终止空字符被 source 的第一个字符覆盖,并且在 destination 中将两者连接形成的新字符串的末尾包含一个空字符。

但是你不一定一个终止空字符,因为你没有零初始化full:

char full[100] = {};

无论如何,您应该使用 std::string

关于c++ - strcat访问冲突写位置c++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29054528/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com