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

} 

I am trying to create a string array with count elements. I used fgets function to read elements into the array using for loops. But when i tried to print the elements the last one is missing from the std output. I tried using count =8;

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

These were my inputs. But 200 won't get printed..

Achal
  • 11,821
  • 2
  • 15
  • 37
Rajesh Sri
  • 159
  • 1
  • 7

1 Answers1

0

Try this version, issues addressed in comments.

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;
}
Achal
  • 11,821
  • 2
  • 15
  • 37
  • Unless you check the return of `scanf` you cannot know whether you have valid values in `row, col`. `getchar();` alone is insufficient to clear `stdin` (there can be more than the `'\n'`) `char **array = malloc (row * sizeof *array);` -- if you size your allocation using the dreferenced pointer, you will never get your type-size wrong. `array[i]` is more readable. You should check the return of `fgets`. Otherwise, a good example, but it is always better to add a few paragraphs explaining what the other person did wrong and how what you did fixes it. Comments alone are a bit terse. – David C. Rankin Jan 06 '19 at 18:47