1.11M Members

Program not working as expected

 
0
 

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

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

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

 
1
 

Also don't forget to free the memory after use

for(j=0;j<noe;j++){
              free(p[i]);
        }
	free(p);
 
0
 

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?

 
0
 

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)

You
This article has been dead for over six months: Start a new discussion instead
Post:
Start New Discussion
View similar articles that have also been tagged: