gpt4 book ai didi

我可以使用 fgets 来接受字符指针数组中的字符串而不是 scanf

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

虽然下面的代码工作正常。但是当我尝试使用 fgets 接受字符串时,它显示“段错误”,因为我想存储可能包含空格的字符串。如何接受字符串(可能包含空格)在字符指针数组中

int main(){
char* nm[5];
char* st;
for(int i=0;i<5;i++)
//fgets(nm[i],30,stdin);
scanf("%ms",&nm[i]);
for(int i=0;i<5;i++)
printf("%s\n",nm[i]);
return 0;
}

最佳答案

nm 是指向 5 个字符的指针,而不是指向 5 个字符串的指针,因此 &nm[2] 是 nm 中第 3 个字符的地址。如果将 nm 更改为

char* nm[5][50];

您将拥有一个 5 x 50 个字符的数组。这应该会阻止段错误。

关于我可以使用 fgets 来接受字符指针数组中的字符串而不是 scanf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51806553/

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