2

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

6
  • 5
    How is student defined? Commented Jan 22, 2020 at 16:13
  • 1
    If name attribute of Student is a pointer, then it makes sense. You are assigning the address of name not the value Commented Jan 22, 2020 at 16:16
  • 1
    You probably need something like strcpy(students[n].name, name) instead of students[n].name = name;. Commented Jan 22, 2020 at 16:16
  • 2
    Never use gets()! Commented Jan 22, 2020 at 16:16
  • 1
    The use of gets() is deprecated! Commented Jan 22, 2020 at 16:17

1 Answer 1

7

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 );
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.