【问题标题】:how to use a loop to get user input of strings如何使用循环获取用户输入的字符串
【发布时间】:2020-11-13 21:49:41
【问题描述】:

我想请用户给我五个问题,然后我想打印出这五个问题。我正在使用 for 循环。它适用于第一个问题,然后停止工作。提前谢谢你。

    #include <stdio.h>
    #include <stdlib.h>

    int main (void)
    {
        char *question [5];
        question[5] = (char*) malloc(5 * sizeof(char));

        for (int i = 0; i < 5; ++i)
        {
             printf("enter question number %i\n", i+1);

             scanf("%[^\n]%*c", question[i]);

             printf("%s\n", question[i]);
        }

        free (question[5]);

       return 0;
   }

【问题讨论】:

  • question[5] = (char*) malloc(5 * sizeof(char)); - 这是为 5 个 chars 分配空间并分配给一个超出 questions 边界的指针。绝对不是你想做的。您需要为question[0]...question[4]中的每一个分配空间

标签: arrays c for-loop pointers


【解决方案1】:

在这里你的代码有问题。

首先,question[5] = malloc(5 * sizeof(char)),在最后一个索引处为 char 指针数组分配 5 个字符。这不是你想要的,你想要的是一个由 5 个字符指针组成的数组,它们都有足够的内存来保存字符串。

#include <stdio.h>
#include <stdlib.h>

int main (void) {
        char *question [5];
        
        for (int i = 0; i < 5; ++i)
        {
            question[i] = malloc(sizeof(char) * 256); //n is the maximum length of the string
            printf("enter question number %i\n", i+1);

            fgets(question[i],256 ,stdin);
            
            printf("%s\n", question[i]);
        }

        for (int i = 0; i < 5; i++) {
            free(question[i]);
        }


       return 0;
}

因此,在上面的代码中,我为字符串数组(字符指针)的每个索引分配了 256 个字符,然后将用户输入写入它们。现在每个索引都包含一个用户输入的字符串。

最后也以相同的方式通过遍历每个索引并释放分配的内存来释放。

【讨论】:

    【解决方案2】:

    你好像不明白什么是动态分配和什么是二维数组。

    要做你想做的事情,你需要创建一个二维数组来将你的“5个字符串”保存到每个一维数组中。

    [0] => ㅁㅁㅁㅁㅁ...问题1

    [1] => ㅁㅁㅁㅁㅁ...问题2

    [2] => ㅁㅁㅁㅁㅁ...问题3

    [3] => ㅁㅁㅁㅁㅁ...问题4

    [4] => ㅁㅁㅁㅁㅁ...问题5

    试试这个

    #include <stdio.h>
    #include <stdlib.h>
    
    int main (void)
    {
        char **question = (char **) malloc(5 * sizeof(char*));
    
        for (int i = 0; i < 5; ++i)
        {
             question[i] = (char*) malloc(sizeof(char) * length you want);
    
             printf("enter question number %i\n", i+1);
    
             scanf("%[^\n]%*c", question[i]);
    
             printf("%s\n", question[i]);
        }
    
        for (int i = 0; i < 5; ++i) free(question[i]);
    
        free(question);
    
       return 0;
    

    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-23
      • 1970-01-01
      • 1970-01-01
      • 2017-03-31
      • 1970-01-01
      相关资源
      最近更新 更多