Search code examples
carrayspointersstructc-strings

Wrong assignment in string struct variable in C


Please help me with this code. Why same name is assigned to all the different structs? I'm noob to pointers and arrays in C.

struct student
{
    char *name;
    int reg_no;
};
typedef struct student student;

int main()
{
    char choice = 'y';
    char name[30];
    int rg;
    student students[5];
    int n = 0;
    while(choice != 'n')
    {
        printf("enter student's name\n>>");
        gets(name);
        printf("enter student's reg_no\n>>");
        scanf("%d",&rg);
        getchar();
        students[n].name = name;
        students[n].reg_no = rg;
        printf("enter details of more students (y/n)\n>>");
        scanf("%c",&choice);
        getchar();
        n++;
    }
    for(int i=0;i<n;i++)
    {
        printf("Details of student%d :\n",(i+1));
        printf("Name : %s\n",students[i].name );
        printf("Reg no. : %d\n\n",students[i].reg_no );
    }
    return 0;
}

Running in console :

enter image description here

Edit : Added student struct


Solution

  • In this statement

    students[n].name = name;
    

    the data member name of all elements of the array students gets the same address of the local variable name.

    You need to declare the data member name of the structure as a character array and use either the C standard function strcpy or strncpy to copy the content of the local variable name to the data member name.

    For example

    #define N 30
    
    struct student
    {
        char name[N];
        int reg_no;
    };
    
    typedef struct student student;
    
    int main( void )
    {
        char choice = 'y';
        char name[N];
        //…
    

    Pay attention to that the function gets is an unsafe function and is not supported by the C Standard. Instead use the standard C function fgets.

    For example

    #include <string.h>
    
    //…
    
    fgets( name, sizeof( name ), stdin );
    name[strcspn( name, "\n" )] = '\0';
    
    //…
    strcpy( students[n].name, name );