#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
- 2
- 309876567
- 67564746
- 111
- 20043
- 75647
- 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/