【问题标题】:strcat Access violation writing location c++strcat 访问冲突写入位置 c++
【发布时间】:2015-03-14 21:41:04
【问题描述】:

我得到一个错误的阅读:

Homework6_10_7.exe 中 0x5AAF40D9 (msvcr120d.dll) 处未处理的异常:>0xC0000005:访问冲突写入位置 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(full, last); 你知道full 最好已经包含一个有效的终止字符串,对吧?您的目前不确定。
  • 你有一个错误。你没有使用std::string

标签: c++ visual-studio-2013 strcat


【解决方案1】:

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

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

char full[100] = {};

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

【讨论】:

  • 或者,如果您不觉得零填充您将要覆盖的缓冲区,则只需在剩余代码之前添加*full = 0;。当然,也可以完全摆脱last,直接将姓氏直接读入full(因为无论如何它都会在哪里结束)。
  • 谢谢!是的,我想只使用一个字符串,但这个任务特别需要一个 cstring >
【解决方案2】:

打印完整字符串时,字符串的最后一个字符不为空,这就是问题所在 尝试在像这样附加到完整字符串之前添加它

for (int i = 0; i < 100; i++)
    full[i] = '\0';

或者你可以简单地这样做

char full[100] = {};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多