I'm trying to input a string of characters to a pointer member of char type of an array of structure. The program is terminating after it receives the string for the member name of emp[0]. My code:
#include<stdio.h>
struct Employee
{
char *name;
int salary;
};
int main()
{
struct Employee emp[3];
int i;
for(i=0;i<3;i++)
{
scanf("%s%d",emp[i].name,&emp[i].salary);
}
printf("\nOutput:");
for(i=0;i<3;i++)
{
printf("\n%s%d",emp[i].name,emp[i].salary);
}
return 0;
}
When without array, the following code for some variable emp
is working fine:
scanf("%s%d",emp.name,&emp.salary);
Any suggestions? Thanks in advance.
The
name
field instruct Employee
is a pointer. You never give that pointer a value, but you pass it toscanf
which then attempts to dereference it. Dereferencing an uninitialized pointer invokes undefined behavior.Instead of using a
char *
forname
, make it an array large enough to hold whatever value you expect: