【问题标题】:Copying strings to an array将字符串复制到数组
【发布时间】:2020-10-22 22:09:38
【问题描述】:

在我的代码输出中,我发现我正在打印的字符串都是(null),即使我输入了count字符串

char name[31];
char *names[32];
int count = 5;
for (int i =0; i<count;i++) {
        scanf("%s",name);
        names[i]=(char*)malloc(strlen(name)+1);
        strcpy(names[i],name);
    }

for (int i =0; i<count;i++) {
    printf("%d: %s\n",i+1,names[count]);
}

【问题讨论】:

  • 可能是错字,但printf("%d: %s\n",i+1,names[count]); 应该是printf("%d: %s\n",i+1,names[i]); - 否则,您将打印一个未分配的字符串。

标签: c c-strings strcpy


【解决方案1】:

也许您应该使用names[i] 而不是names[count]

for (int i = 0; i < count; i++) {
    printf("%d: %s\n", i+1, names[i]);
}

【讨论】:

    【解决方案2】:

    您正在使用 count 索引名称,但您的代码仅将字符串初始化为 count - 1。 以这种方式更改 printf:

    printf("%d: %s\n",i+1,names[i]);
    

    应该可以解决问题。

    【讨论】:

      【解决方案3】:

      你的错误在printf函数,你需要这样修改:

      printf("%d: %s\n",i+1,names[count]); => printf("%d: %s\n",i+1,names[i]);

      【讨论】:

        猜你喜欢
        • 2020-11-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-11-13
        • 2015-03-23
        相关资源
        最近更新 更多