Reputation: 1442
int ReadNames(char ***Names, int *n)
{
int i, k;
char name[100];
printf("Enter how many names\n");
scanf("%d", n);
/* Allocate memory and read names */
*Names=(char **)malloc((*n)*sizeof(char *));
for(i=0;i<(*n);i++)
{
*(*Names+i)=(char*)malloc(sizeof(name));
gets(name);
strcpy(*(*Names+i),name);
}
for(i=0;i<(*n);i++)
printf("%s\n",*(*Names+i));
return 1;
}
void main()
{
char **Names;
int n, i;
ReadNames(&Names, &n);
}
This program is running fine...but there is slight difference from what i am expecting. Problem is when i am entering value of 'n' as 3, it is able to read only 2 strings and prints those two strings....ie. it reads n-1 strings and prints n-1 strings. Anything wrong in my code.
Upvotes: 0
Views: 397
Reputation: 10516
1.Please Do not use gets()
use fgets()
instead.
fgets(name, sizeof name,stdin);
remove newline at the end of input.
2.In your case after giving input at scanf()
you should press Enter
gets()
is taking this newline as input for first string.
there are few simple solutions
Use getchar()
to read newline after scanf()
or
Add a space after %d
in scanf()
or
if you are working on windows you can use fflush()
3.Do not cast result of malloc because it returns generic pointer and it can be assigned with out cast
Upvotes: 1
Reputation: 1281
just add getchar()
after scanf()
so that each '\n'
gets disposed of while taking input.
Your code will be
int ReadNames(char ***Names, int *n)
{
int i, k;
char name[100];
printf("Enter how many names\n");
scanf("%d", n);
getchar(); // eats unnecessary '\n' in the buffer
/* Allocate memory and read names */
*Names=(char **)malloc((*n)*sizeof(char *));
for(i=0;i<(*n);i++)
{
*(*Names+i)=(char*)malloc(sizeof(name));
gets(name);
strcpy(*(*Names+i),name);
}
for(i=0;i<(*n);i++)
printf("%s\n",*(*Names+i));
return 1;
}
void main()
{
char **Names;
int n, i;
ReadNames(&Names, &n);
}
Upvotes: 2
Reputation: 409136
The problem you are having is most likely because the scanf
you use to get the count leaves the newline still in the buffer. This means that the first gets
call reads that single newline and you add that empty line.
A simple and easy solution is to add a space after the scanf
format, which tells scanf
to skip all whitespace. Like
scanf("%d ", n);
Upvotes: 1