gpt4 book ai didi

c - 中止陷阱 : 6 in C when using strcpy on MacOS

转载 作者:太空宇宙 更新时间:2023-11-04 01:00:36 25 4
gpt4 key购买 nike

我正在编写一些代码,将字符串作为输入并将其反向返回。

当我输入字符串时,出现“abort trap: 6”错误。我认为问题在于我对 strcpy 的使用(误用?),但 GDB 没有帮助,关于此错误的其他问题和 strcpy 也没有帮助我理解为什么我会收到此错误。

我在我的代码中添加了一些注释来解释预期的功能。

感谢您提供的任何帮助或阅读 Material !

        #include <stdio.h>
#include <string.h>

int main()
{
char line[1024];
fgets(line,sizeof(line),stdin);
int size = strlen(line);
for(int I = 0; I <size-I;I++)
{
char temp;
int relative_size = size-I;
strcpy(&temp,&line[I]);//??copies Ith character of line to temp??
strcpy(&line[I],&line[relative_size]); //??swaps characters at [I] and [size-I]??
strcpy(&line[relative_size],&temp);
}
printf("%s", line);
return 0;
}

最佳答案

strcpy 不会单独复制字符。它复制字符串。该字符串是后跟\0 终止符的字符数。

 strcpy(&temp,&line[I]);

上面的 strcpy 尝试复制一个从第 I 个字符开始直到结束(到达第一个\0)的字符串到 &temp 指定的地址。因为 temp 是单个 char 变量,实际上您正在破坏堆栈框架并将内容写入其他变量。

你应该使用类似这样的方法来获取第 I 个字符

temp = line[I];

关于c - 中止陷阱 : 6 in C when using strcpy on MacOS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41156398/

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