首页 > 解决方案 > for 循环没有考虑执行的最后一个循环

问题描述

#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;

} 

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

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

这些是我的投入。但是200不会被打印出来..

标签: cmultidimensional-arrayc-strings

解决方案


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

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;
}

推荐阅读