gpt4 book ai didi

c++ - 运行时检查失败 #2 - 变量 'sample' 周围的堆栈已损坏

转载 作者:行者123 更新时间:2023-11-30 01:48:35 25 4
gpt4 key购买 nike

我有这个数组,我在尝试 strncat 时遇到了这个错误:运行时检查失败 #2 - 变量“sample”周围的堆栈已损坏。

char sample[] = "red";
char * y = "blue";


cout << strncat(sample, y, sizeof(sample));

确实正确执行了strncat,但是在退出main函数后,出现Run-time check failure。

编辑:只需将大小添加到目标字符数组即可解决此问题!

char sample[10] = "red";
char * y = "blue";


cout << strncat(sample, y, sizeof(y));

最佳答案

sample 中没有空间来附加字符串 y

还有,你好像误解了strncat的第三个参数是什么是。它不是目标的大小(第一个参数),而是要追加的源(第二个参数)的字符数量。

试试这个:

#include <cstring>
#include <iostream>

int main ()
{
// space for red space for blue space for zero
// ^ ^ ^
char sample[3 + 4 + 1] = "red";
const char* y = "blue";
// number of chars in y
// ^
std::cout << strncat (sample, y, strlen (y)) << std::endl;
}

关于c++ - 运行时检查失败 #2 - 变量 'sample' 周围的堆栈已损坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30294082/

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