-3

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?

Suraj Jain
  • 4,463
  • 28
  • 39
vchitta
  • 2,043
  • 9
  • 28
  • 37
  • 5
    You need to get a book on C programming and learn about pointers. It's important to get the basics straight from the beginning, or it *will* cause trouble for you later. – Cody Gray - on strike Jul 09 '11 at 09:26

3 Answers3

8

You are not allocating memory for emp. Before using emp, try

emp = malloc(sizeof(*emp));
cnicutar
  • 178,505
  • 25
  • 365
  • 392
  • 2
    sizeof(emp), otherwise you get the size of a pointer... – yankee Jul 09 '11 at 09:26
  • 9
    @yankee No, `emp` is the pointer, `*emp` is the object pointed to :-) – cnicutar Jul 09 '11 at 09:27
  • Ok, learned something about C today :-). – yankee Jul 09 '11 at 09:40
  • @nil To format my post, do i need to just place my code in a pair of ` ? like `emp = malloc(sizeof(emp));` or stackoverflow does have any document or tool to do that befor posting? Further, it is long time i used c and lost basics, you are right. I am currently using java language these days. Also, can you point me to the rules (posting rules ) of StackOverflow? – vchitta Jul 09 '11 at 09:56
  • 1
    @vchitta http://stackoverflow.com/faq – cnicutar Jul 09 '11 at 10:05
1

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.

Ken Y-N
  • 14,644
  • 21
  • 71
  • 114
Finn
  • 23
  • 4
0

You need not to use pointer to struct nor printf.

#include<stdio.h>
int main()
{
    puts("empname :Kumar");
    puts("empage :30");
    return 0;
}
kamae
  • 1,825
  • 1
  • 16
  • 21