0

I've got this structure, a simple one that holds student name and marks. When I'm trying to read user input into the name(char array), I get a warning indicating something on the lines of :

format %s expects char *, but has char*[20]

I know this is because char arrays cannot be assigned in C, so strcpy has to be used. This question on SO has a good reasoning. However,how do I fix the warning in my program? Don't think I can use strcpy here.

#include <stdio.h>


typedef struct _student
{
    char name[20];
    unsigned int marks;
} student;


void read_list(student list[], int SIZE);
void print_list(student list[], int SIZE);

int main()
{
    const int SIZE=3;
    student list[SIZE];

    //function to enter student info.
    read_list(list, SIZE);
    //function to print student info
    print_list(list, SIZE);
    return 0;
}

void read_list(student list[], int SIZE)
{
    int i;
    char nm[20];
    for (i=0;i<SIZE;i++)
    {
        printf("\n Please enter name for student %d\n", i);
        scanf("%s",&list[i].name);

        printf("\n Please enter marks for student %d\n", i);
        scanf("%u", &list[i].marks);
    }

}

void print_list(student list[], int SIZE)
{
    int i;
    printf("\t STUDENT NAME  STUDENT MARKS\t \n");

    for(i=0;i<SIZE;i++)
    {
        printf("\t %s \t %u\n", list[i].name, list[i].marks);   
    }
}

The program does give a correct output, but the warning remains.

Community
  • 1
  • 1
Manish Giri
  • 3,562
  • 8
  • 45
  • 81

4 Answers4

2

Try this code:

    for (i=0;i<SIZE;i++)
    {
        printf("\n Please enter name for student %d\n", i);
        scanf("%s",list[i].name);

        printf("\n Please enter marks for student %d\n", i);
        scanf("%u", &list[i].marks);
    }

This is because & used in scanf statement is to get the address.

In your case you use array name i.e. name and array name itself is providing the address. Remember array name gives the base address of an array.

thumbmunkeys
  • 20,606
  • 8
  • 62
  • 110
tod
  • 1,539
  • 4
  • 17
  • 43
0

change scanf("%s",&list[i].name); to scanf("%s",list[i].name);. Delete &. Because basically array name represents base address. No need to mention address of array for scanning the string.

Anbu.Sankar
  • 1,326
  • 8
  • 15
0

Remove the & in the scanf that scan in a string using %s to eliminate the warning. So change

scanf("%s",&list[i].name);

to

scanf("%s",list[i].name);

This is because the name of the char array decays to a pointer to its first element

Spikatrix
  • 20,225
  • 7
  • 37
  • 83
0

line 33:

scanf("%s",&list[i].name);//wrong

scanf("%s",list[i].name);//right

The name of an array is synonym for the location of the initial element , thus in your code, variable 'name' is the address of name[0]. You don't need to use & on 'name' to get the address of the array.Just use 'name' itself.