c - for 循环没有考虑执行的最后一个循环

标签 c multidimensional-array c-strings

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
        int count;
        scanf("%d",&count);
        char **array;
        array = (char **) malloc(sizeof(char* ) * count);
        for(int i=0;i<count;i++)
        {
                *(array +i) = (char *)malloc(sizeof(char) * 1000);
        }
        for(int i=0;i<count;i++)
        {
                fgets(*(array + i) , 1000 , stdin);
        }

        for(int i=0;i<count;i++)
        {
                printf("%s:::",*(array+i));
        }
        printf("\n");
        return 0;

} 

我正在尝试创建一个包含 count 元素的字符串数组。我使用 fgets 函数使用 for 循环将元素读入数组。 但是当我尝试打印元素时,标准输出中缺少最后一个元素。 我尝试使用 count =8;

  1. 1
  2. 2
  3. 309876567
  4. 67564746
  5. 111
  6. 20043
  7. 75647
  8. 200

这些是我的输入。 但 200 不会被打印..

最佳答案

尝试这个版本,评论中解决了问题。

int main(void) {
        int row, col /* 1000 */;
        scanf("%d%d",&row, &col);
        getchar();/* to clear stdin buffer */
        char **array = malloc(sizeof(char*) * row);
        for(int i=0;i < row; i++) {
                /* allocate memory */
                *(array +i) = malloc(sizeof(char) * col);
                /* scan the data */
                fgets(*(array + i), col, stdin); /* fgets add \n at the end of buffer if read */
                array[i][strcspn(array[i], "\n")] = 0; /* remove trailing \n */
                /* print it */
                printf("%s\n",*(array+i));
        }
        printf("\n");
        /* free dynamically allocated memory @TODO */
        return 0;
}

关于c - for 循环没有考虑执行的最后一个循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54058987/

相关文章:

c - 直接指向 C 中的文本不是不可能吗?

c - 来自文本文件的多维数组

mocking - 检查模拟类中的嵌套数组结构

C 尝试理解 select() 和 FD_ISSET()

r - 数组索引保留结构

c# - 如何检查数组是否存在?

c - 为什么我用 C 编写的以下 getString() 函数不起作用?

c++ - 如何通过外部 “C” ABI公开std::vector <std::string>?

c - 由于内存耗尽而从 NULL == malloc() 恢复的策略

c - 高效地读取 C 中的扁平化文件