gpt4 book ai didi

c - 由于 strcpy 和 strcat 导致的段错误

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

为什么我在下面的代码中出现段错误?我希望它打印第一个单词“嘿”。我知道还有其他方法可以完成我想做的事情,但我想知道为什么会失败。请帮忙。

int main(){
char string[30], ops1[30], temp;
char t[2];
int op1, i=0;
strcpy(string, "hey ssup");
while(string[i] != '\0') {
if(string[i]!= ' '){
temp = string[i];
strcpy(ops1, &temp);
i++;
while(string[i] != ' ') {
temp = string[i];
strcpy(t, &temp);
strcat(ops1, t);
}
}
i++;
}
printf("%s", ops1);
return 0;
}

最佳答案

如果是单个字符,则不需要 strcpy()strcat() 。您可以通过index直接复制,如ops1[j] = string[i];

您还忘记添加 ops1[j] = '\0'; 字符串终止符。您需要指定 \0 来结束字符串。

您的 while(string[i] != ' ') 不会结束 (是一个无限循环),因为 i 没有改变在那个循环中。这个问题可以通过单个循环来解决。

试试这个代码:-

#include <stdio.h>
int main()
{
char string[30], ops1[30];
char t[2];
int op1, i, j;
strcpy(string, "hey ssup");

j = 0;
i = 0;
while (string[i] != '\0')
{
ops1[j++] = string[i]; // coping

if (string[i] == ' ') // stops when first ' ' found
{
break;
}
i++;
}
ops1[j] = '\0';
printf("%s", ops1);
return 0;
}

输出:-

hey

关于c - 由于 strcpy 和 strcat 导致的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51523276/

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