0

I did a program to understand the concept of structures and returning struct from a function

struct student
{
    char name[20];
    int age;
    char subject[20];
    int marks;
    int rollno;
}sheet;
struct student display()
{

    sheet.name[20]="Swathi";
    sheet.age=21;
    sheet.subject[20]="Mathematics";
    sheet.marks=85;
    printf("Enter roll no.:");
    scanf("%d",&sheet.rollno);

}
int main()
{   
    struct student sheet1;
    sheet1=display();
    printf("Name:%s",sheet.name);
    printf("Age:%d",sheet.age);

}

I am getting 2 warning messages

warning: assignment makes integer from pointer without a cast [-Wint-conversion]
  sheet.name[20]="Swathi";
warning: assignment makes integer from pointer without a cast [-Wint-conversion]
  sheet.subject[20]="Mathematics";

Why is it happening? How should I change this?

Pra
  • 39
  • 8

2 Answers2

1

This here:

sheet.name[20]="Swathi";

Just gets the address of "Swathi" (which is read only), implicitly casts that address to a char (making it useless), and then assigns that to sheet.name[20] (which is out of bounds, so undefined behavior). Instead, try this:

strcpy(sheet.name, "Swathi");

Likewise with sheet.subject[20]="Mathematics";. Also note that your struct student display() isn't returning anything, it should be void display() and struct student sheet1; isn't needed.

Blaze
  • 16,736
  • 2
  • 25
  • 44
  • Rather than posting yet another answer to this very common FAQ, consider close-voting it. A list of suitable dupe targets can be found in the [C tag wiki](https://stackoverflow.com/tags/c/info). – Lundin Feb 26 '20 at 08:56
0

It worked

struct student
{
    char name[20];
    int age;
    char subject[20];
    int marks;
    int rollno;
}sheet;
struct student display()
{

    strcpy(sheet.name, "Swathi");
    sheet.age=21;
    strcpy(sheet.subject,"Mathematics");
    sheet.marks=85;
    printf("Enter roll no.:");
    scanf("%d",&sheet.rollno);

}
int main()
{   
    display();
    printf("Name:%s",sheet.name);
    printf("Age:%d",sheet.age);

}
Pra
  • 39
  • 8