having problem with struct memory allocation.Help please

What is wrong with the code

#include<stdio.h>
#include<string.h>
struct idendity{
 char name[8];
int age;
char gender;
};
typedef struct idendity id;

id boys[20];
void main()
{
int p,q,n=0;

printf("How many boys?:");
scanf("%d",&n);

for(p=0;p<n;p++)
{  printf("Student %d name:",(p+1));

scanf("%s",boys[p].name);      

printf("\nStudent %d gender:",(p+1));

scanf("%c",&boys[p].gender);

printf("\nStudent %d age:",(p+1));

scanf("%d",&boys[p].age);
}
printf("\n");
for(p=0;p<n;p++)
{for(q=n-1;q>p;q--)
{
if(boys[p].name==boys[q].name)
{
printf("Student[%d] (%s) and Student[%d] (%s) are actually same person.\n",(p+1),boys[p].name,(q+1),boys[q].name);

}

}
}
}

I think it’s because i haven’t allocated memory for it.It works fine if I set the struct variables before compiling.But doesn’t work if want to take input.But I don’t get this stuff.I have declared an array of 20 elements .Then why I need to take memory again?
This may be a trivial one.But I m a new in C.So,I m not much familiar with the memory and pointer stuff.Hope will get help.Thanks.

I hope you are aware that the user can input at most 20 for the first question “How many boys?”

Because you have declared id boys[20]

Next, your program is fine within the domain, but the problem is when you’re asking for the gender.

scanf("%c",&boys[p].gender);

This will simply take the previous newline character and hence next statement in the printf will be prompted on the screen. You can sort out this issue by adding a dummy getchar() or manipulating the scanf to incorporate the newline fed previously.

Here is the modified code snippet

printf("Student %d name:",(p+1));
scanf("%s",boys[p].name);
getchar();                                    //Notice this!
printf("\nStudent %d gender:",(p+1));
scanf("%c",&boys[p].gender);
printf("\nStudent %d age:",(p+1));
scanf("%d",&boys[p].age);

Next you are lacking something in the name comparison part, try to figure it out yourself. Because that is an easy part. Good Luck!

1 Like
//