0

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();
    }
2
Contributors
2
Replies
4
Views
5 Years
Discussion Span
Last Post by general2012
0

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!)

Edited by NP-complete

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.