×

# having problem with struct memory allocation.Help please

 0 What is wrong with the code #include #include 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;pp;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. asked 01 Aug '13, 21:18 11●11●17●16 accept rate: 0% 3★sobhagya 2.7k●13●27●47

 1 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! answered 02 Aug '13, 00:52 8.7k●19●48●98 accept rate: 9%
 toggle preview community wiki:
Preview

By Email:

Markdown Basics

• *italic* or _italic_
• **bold** or __bold__
• image?![alt text](/path/img.jpg "title")
• numbered list: 1. Foo 2. Bar
• to add a line break simply add two spaces to where you would like the new line to be.
• basic HTML tags are also supported
• mathemetical formulas in Latex between \$ symbol

Question tags:

×1,918
×1,491
×107
×26
×16
×10

question asked: 01 Aug '13, 21:18

question was seen: 1,172 times

last updated: 02 Aug '13, 00:52