【问题标题】:How to accept character array input into a structure in C?如何接受字符数组输入到 C 中的结构中?
【发布时间】:2015-01-15 15:58:46
【问题描述】:

我有这个结构,一个包含学生姓名和分数的简单结构。当我尝试将用户输入读入名称(字符数组)时,我收到一条警告,指示以下内容:

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

我知道这是因为 char arrays 不能在 C 中赋值,所以必须使用 strcpy。 SO 上的这个question 有一个很好的理由。但是,如何修复程序中的警告?不要以为我可以在这里使用 strcpy。

#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);   
    }
}

程序确实给出了正确的输出,但警告仍然存在。

【问题讨论】:

  • 在此处删除&amp; scanf("%s",&amp;list[i].name);
  • 程序确实给出了正确的输出,因为对于静态分配的数组arrarr&amp;arr 的值是相同的。

标签: c arrays struct


【解决方案1】:

scanf("%s",&amp;list[i].name); 更改为scanf("%s",list[i].name);。删除&amp;。因为基本上数组名代表基地址。扫描字符串时无需提及数组地址。

【讨论】:

    【解决方案2】:

    删除使用%s 扫描字符串的scanf 中的&amp; 以消除警告。所以改变

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

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

    这是因为char 数组的名称衰减为指向其第一个元素的指针

    【讨论】:

      【解决方案3】:

      试试这个代码:

          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);
          }
      

      这是因为&amp;用在scanf语句中是为了获取地址。

      在您的情况下,您使用数组名称,即name,而数组名称本身就是提供地址。记住数组名给出了数组的基地址。

      【讨论】:

        【解决方案4】:

        第 33 行:

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

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

        数组的名称是初始元素位置的同义词,因此在您的代码中,变量“名称”是名称 [0] 的地址。你不需要在'name'上使用&来获取数组的地址。只需使用'name'本身。

        【讨论】:

          猜你喜欢
          • 2017-08-08
          • 1970-01-01
          • 2011-09-08
          • 2021-08-31
          • 2017-05-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-06-30
          相关资源
          最近更新 更多