问题
What is wrong with this code snippet? i am getting Segmentation fault!
#include<stdio.h>
int main()
{
struct {
char* name;
int age;
} *emp;
char* empname = "Kumar";
int empage = 31;
emp->name = empname;
emp->age = empage;
printf("empname :%s\n",emp->name);
printf("empage :%d",emp->age);
return 0;
}
And how to correct this program to work?
回答1:
You are not allocating memory for emp. Before using emp, try
emp = malloc(sizeof(*emp));
回答2:
if you test your code putting in compilation -Wall, the terminal says you that 'emp' is uninitialized therefore you must allocate in dynamic way 'emp' (malloc etc. etc.).
int len_struct = sizeof(*emp);
emp = malloc(len_struct);
PS: This is my advice : i prefer create a struct in global memory (in Data) because i think that this struct you would use in future in the prg.
回答3:
You need not to use pointer to struct nor printf.
#include<stdio.h>
int main()
{
puts("empname :Kumar");
puts("empage :30");
return 0;
}
来源:https://stackoverflow.com/questions/6633916/segmentation-fault