copy string into a structure

all i am trying to do here is to copy a string input given by user into an arry decleared inside a structure.but my code is not working. anyone please explain to me why this code isnt working

    #include<stdio.h>
    #include<string.h>
    typedef struct{
    int count;
    char name[20];
    }student;
    int main()
    {
    student *p;
    p=(student *)malloc(sizeof(student));
    char input_name[20];
    gets(input_name);
    strcpy(p->name[(p->count)++],input_name);
    printf("%s",p->name[(p->count)++]);
    getch();
    }

Recommended Answers

All 2 Replies

Why its not working:
1. p->count is never initialized to anything.
But the main problem is this:
2. You are trying to copy a C-string to a character. p->name[any index] refers to a single character and not a C-string. So strcpy fails.
3. Again, you want to print a C-String (with that %s) but you are really trying to feed a character to that %s. Result: your code crashes.

The fix:

    #include<stdio.h>
    #include<string.h>

    typedef struct{
        int count;
        char name[20];
    }student;

    int main()
    {
        student *p;
        p = (student*) malloc(sizeof(student));
        char input_name[20];
        gets(input_name);
        strcpy(p->name, input_name);
        printf("%s", p->name);
        getch();
    }

Now, a few tips to improve:
1. Use fgets instead of gets.
2. Once you use fgets you may as well want to use strncpy to make the copy overflow safe.
3. You may want to include stdlib.h for malloc. In that case, the cast would be redundant (And this should be the case!)

thanx. now it is quite clear to me.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.