gpt4 book ai didi

c - 尝试将 strcpy() 用于 2D 字符数组时出现段错误?

转载 作者:太空宇宙 更新时间:2023-11-04 03:41:10 27 4
gpt4 key购买 nike

我正在尝试编写一个函数,它接受两个字符串,将它们连接起来,然后将它们写入一个二维数组。我一直在搞乱不同的事情,并查看其他帖子无济于事。当我试图将连接的字符串写入 char 数组时,段错误似乎发生在最后一个 strcpy 中。如果该行被注释掉,程序似乎运行良好。

void saveToArray(char *command1, char *command2)
{
char *saveCommands[30][100];
int *commands = malloc(sizeof(int));
char concatCommand[30];

strcpy(concatCommand, command1);
strcat(concatCommand, " ");
strcat(concatCommand, command2);
strcpy(*&saveCommands[0][*commands], concatCommand);
*commands += 1;
}

对于任何格式问题,我提前表示歉意,因为这是我的第一篇文章,感谢您的任何答复!

最佳答案

这个函数中发生了很多可怕的事情。对于初学者...

int *commands = malloc(sizeof(int));

你没有释放它或返回它,所以它是 100% 的内存泄漏。我看不出您为什么要在堆上而不是堆栈上分配这个整数。

char concatCommand[30];

strcpy(concatCommand, command1);
strcat(concatCommand, " ");
strcat(concatCommand, command2);

这可能会溢出您的缓冲区。

strcpy(*&saveCommands[0][*commands], concatCommand);

*& 是一个空操作(它什么都不做)。您不会将任何内容复制到命令中,因此 *commands 可以是任何内容。最后,saveCommands 中的指针未初始化,因此 strcpy(saveCommands[x][y], "some string") 在实践中基本上总是会出现段错误。我想你可能想要这个:

char saveCommands[30][100]
...
strcpy(&saveCommands[0][*commands], concatCommand);

关于c - 尝试将 strcpy() 用于 2D 字符数组时出现段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28491091/

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