Monday, July 27, 2009

Why isn't this structure in C working properly?

#include %26lt;stdio.h%26gt;


#include %26lt;conio.h%26gt;





struct student


{


char name[16];


char dpt[3];


};





void main()


{


student one[3];


for(int i=0;i%26lt;3;i++)


scanf("%s%s",one[i].name,one[i].dpt);


for(i=0;i%26lt;3;i++)


printf("\nThe name is: %s, and department is: %s.",one[i].name,one[i].dpt);


getch();


}





output:





karn


ity


deep


bty


ankan


civ


The name is: karn, and department is: itydeep


The ... : deep, ... : btyankan


The ... : ankan, ... : civ





What the hell's going on?? Why is the same string input being stored in two variables??

Why isn't this structure in C working properly?
Impressive, I thought I was the only one who could pull off an error like this and stare at it for hours! When the department is scanned in there are 4 chars, 'ity\0', the \0 is overwritten on the next scanf giving you an extended dpt string and a pointer into the middle of that for the next name.

salary survey

No comments:

Post a Comment