0
typedef struct employee
{
    int age;
    char name[30];
} emp_t;

emp_t * e;

int main( )
{
    printf("\nName : ");
    scanf("%s", &e->name);
    return 0;
}

this code compiles but when I try to enter my name such as "mukesh" it throughs out an error Can somebody explain why this is happening In the structure I used char name[] as well as char * name......did't work I don't understand why???????

do I need to allocate memory dynamically to the structure employee and then assign it it to e->name

1
  • What is exactly your error? My guess is you have a segmentation fault Commented Apr 1, 2011 at 13:00

3 Answers 3

3

Yes, you must allocate the storage before you can access it. Otherwise you'll just be pointing at some random location in memory.

Try this:

typedef struct employee
{
    int age;
    char name[30];
} emp_t;

emp_t * e;

int main( )
{
    e = malloc(sizeof(emp_t));
    printf("\nName : ");
    scanf("%s", e->name);
    return 0;
}
Sign up to request clarification or add additional context in comments.

1 Comment

side note: in C, the cast is unnecessary. you can simply write e = malloc(sizeof(emp_t));
2

you should use

scanf("%s",e->name)  // name is itself an array, so need not to use &

Comments

1

Yes, you have to allocate memory for what e is pointing first. Something like:

e = (emp_t*) malloc(sizeof(emp_t));

Also, as some other noted above (and just for completeness), you should be using e->name instead of &e->name), as a name of an array (name) is implicitly the address of its first byte.

2 Comments

Thanks, Diego but is there any specific reason why can't I do scanf("%s", &e->name); why it does not work
@mukesh : no need to use & when you are scaning for array. name of array variable itself refers to first element location.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.