开发者

segmentation fault in C

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("ent开发者_如何学Pythoner 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;
}


  • You need to allocate memory for the name field: p[i].name = (char*)malloc(MAX_NAME_LEN)
  • Also, the scanf("%s", &p[i].name) should read scanf("%s", p[i].name).


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];


You don't need the & operator when scanf'ing to pointer. And you need to malloc p[i].name

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


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


You forgot to allocate memory for p[i].name.


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.


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]).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜