Something is not going right in the following code. I am taking an array of strings from user and printing at the same time. Array can have noe no. of strings, as noe is entered by user.

#include <stdio.h>
int main(){
    char **p;
    int noe=0,i=0,j=0;
        scanf("%d", &noe);
        p=malloc( noe * sizeof(char *) );
        for(j=0;j<noe;j++)
        {
            p[j]=malloc( 25* sizeof(char *) );

        }
        for(j=0;j<noe;j++){
            //takes events as x y time
            gets(p[j]);
            puts(p[j]);
        }

return 0;
}

When I give noe as 5,( the no. of strings user wants to enter), loop goes for 4 times only and I am able to give input for 4 strings??

Expected Output:-

5
Alice 
Marry
Jane
Allen
john

Actual Output :-

5

Alice
Marry
Jane
Allen

Why there is an empty line in output? and Why I am not allowed to enter 1 last input

gets(p[j]); //use scanf
puts(p[j]); //use printf

It worked!! But what's the reason for this inconsistency?

Also don't forget to free the memory after use

for(j=0;j<noe;j++){
              free(p[i]);
        }
	free(p);
commented: Was searching the forum and found this,thanks +1

That was nice article, n yeah! I really forgot to add free,
btw, fgets also not working exactly :(
It is also showing same behavior as gets...

btw, thanks for the help! why do you think fgets and gets are behaving this way?

Member Avatar for v3ga

The enter u put when u input 5 will remain in the input buffer as a newline.
Gets reads from input buffer until it sees a newline and then it removes it from the buffer(but does not add it to the string). So the first gets will remove the newline and the second gets will accept the first input and so on. fgets also stops after accepting newline(but fgets adds newline also to the string)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.