开发者

calling character array in stucture

typedef struct employee
{
    int age;
    char name[开发者_如何学Go30];
} 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


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


you should use

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


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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜