segmentation fault in C -
i trying write code, gives me segmentation fault after running program, please sort 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; }
the structure field name wild character pointer.
char* name; you reading user input as:
scanf("%s", &p[i].name); into memory pointed name anywhere.
to fix need dynamically allocate memory pointed name or can change name char array of size 1 greater max length of name possible.
char name[max];
Comments
Post a Comment