Reputation: 2252
I am trying to write this code, but it gives me segmentation fault after running the program, could you please help to sort it out?
#include <stdio.h>
#include <string.h>
typedef struct{
int salary;
char* name;
} employee ;
int main(){
employee p[2];
int i;
for(i=0;i<2; i++){
printf("enter sal ");
scanf("%d", &p[i].salary);
printf("enter name ");
scanf("%s", &p[i].name);
}
for(i=0;i<2; i++){
printf("p %d",p[i].salary);
printf("p %s",p[i].name);
}
return 0;
}
Upvotes: 0
Views: 420
Reputation: 5241
You need to allocate memory for the "name" string in your structure. Do this using malloc() or by declaring name as an array of a given size (char name[SIZE]).
Upvotes: 0
Reputation: 1596
You are not allocating memory for char* name. change your data structure to
typedef struct
{
int salary;
char name[50];
}
or allocate memory using malloc
Upvotes: 1
Reputation: 454912
The structure field name
is just a wild character pointer.
char* name;
you are reading the user input as:
scanf("%s", &p[i].name);
into the memory pointed by name
which could be anywhere.
To fix this you need to dynamically allocate memory pointed to by name
or you can change name
to a char
array of size one greater than the max length of the name possible.
char name[MAX];
Upvotes: 1
Reputation: 29001
You have to reserve memory for the name
member of each instance of employee
:
p[i].name = (char*)malloc(expected_max_size);
just before the scanf
for that variable. Declaring a pointer to char char*
does not assign memory for the actual string pointed to, but just for the pointer itself, and in your example it is not initialized. By using malloc
you reserve a piece of memory and makes the pointer point to it. You have to be careful with bounds checking, because you have to reserve the memory beforehand, enough to hold what the user is writing.
Upvotes: 0
Reputation: 500157
p[i].name = (char*)malloc(MAX_NAME_LEN)
scanf("%s", &p[i].name)
should read scanf("%s", p[i].name)
.Upvotes: 5
Reputation: 60506
You don't need the & operator when scanf'ing to pointer. And you need to malloc p[i].name
scanf("%s", p[i].name);
Upvotes: 1