What is wrong with this code snippet? i am getting Segmentation fault!
#include<stdio.h>
int main()
{
struct {
char* 开发者_Python百科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?
You are not allocating memory for emp
. Before using emp
, try
emp = malloc(sizeof(*emp));
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.
You need not to use pointer to struct
nor printf
.
#include<stdio.h>
int main()
{
puts("empname :Kumar");
puts("empage :30");
return 0;
}
精彩评论