gpt4 book ai didi

c - 初始化指向字符串数组的指针

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

char *arr[100];

如何正确初始化它?这条线还有其他问题吗?我对 C 和一般编程很陌生,很难理解这一点。

这是我的其余代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <cstdlib>
int main ()
{
char ans[100];
int count;
count=0;
char *arr[100];
char *srtarr[100];
while(count<100)
{
if(strcmp(ans,"done\n")!=0)
{
printf("Enter names when done type done:");
fgets(ans,100,stdin);
arr[count]=strdup(ans);
}
printf("%s",arr[count]);
count++;

}
system("pause");
return 0;
}

最佳答案

由于出现逻辑错误,程序正在崩溃。

看看你的 while 循环。

while(count<100)
{
if(strcmp(ans,"done\n")!=0)
{
printf("Enter names when done type done:");
fgets(ans,100,stdin);
arr[count]=strdup(ans);
}
printf("%s",arr[count]);
count++;
}

假设用户输入了

done

作为输入的第一行。 arr[1] 没有设置任何内容。此时,arr[1] 尚未初始化。它指向垃圾。这将导致行中未定义的行为

   printf("%s",arr[count]);

您需要对 while 循环进行一些重新安排。

while(count<100)
{
printf("Enter names when done type done:");
fgets(ans,100,stdin);
if(strcmp(ans,"done\n") ==0 )
{
break;
}

arr[count]=strdup(ans);
printf("%s",arr[count]);
count++;
}

关于c - 初始化指向字符串数组的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26478702/

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