Apoorv singhai Apoorv singhai - 3 months ago 9
C Question

Accessing array of structure using pointer. ( Something wrong with the code)

There is an array of structure, which is passed to accept function so as to store some value in the structure. The loop inside the accept function iterates only single time, only upto scanf.

struct emp
{
int age;
char name[20];
float sal;
};

void display(struct emp *);
void accept(struct emp *);

void main()
{
clrscr();
struct emp E[3];
accept(E);
display(E);
getch();
}

void accept(struct emp *p)
{
int i;
for(i=0;i<3;i++)
{
printf("Enter age, name and sal: ");
scanf("%d %s %f",&(p+i)->age,(p+i)->name,&(p+i)->sal);
}
}

void display(struct emp *p)
{
int i;
for(i=0;i<3;i++)
{
printf("Result: %d %s %f",(p+i)->age,(p+i)->name,(p+i)->sal);
}
}


Please rectify the code.

Answer

In case you are taking input name with space characters, try this way:

scanf("%d %[^\n]s %f",&(p+i)->age,(p+i)->name,&(p+i)->sal);

N.B: I also removed clrscr() and getch() and used int main() instead of void main(). Because these were giving errors.