【问题标题】:Structs and char strings [duplicate]结构和字符字符串[重复]
【发布时间】:2014-09-19 20:41:15
【问题描述】:
#include <stdio.h>
#define MAX 3 // students in class 
#define LEN 20 // max lengths stydent's name

typedef struct {
    char name[LEN];
    int am;
    float tv;
}student;

void read (student board[]) {       //this function should fill the board of structs
    int i;
    for (i=0; i<MAX; i++) {
        printf("\n give student's name");
        scanf ("%s",&board[i].name);
    }

}

void read (student board[]);

int main (void) {
    student class[MAX];
    read (class);
return 0;   
} 

当我尝试编译它时,我得到了这个错误

let2.c:15:3:警告:格式“%s”需要“char ”类型的参数,但参数 2 的类型为“char ()[20]”[-Wformat= ]
let2.c:15:3:警告:格式“%s”需要“char ”类型的参数,但参数 2 的类型为“char ()[20]”[-Wformat=]

【问题讨论】:

    标签: c string struct char


    【解决方案1】:

    在您的scanf 呼叫中丢失&amp;。你想要一个指向字符串第一个字符的指针,而不是指向数组本身的指针:

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

    或者,等效地:

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

    【讨论】:

    • 哇!!如此快速和准确。非常感谢你 !!不是指向数组本身的指针。你能再解释一下吗?
    • 这将是一个很好的机会来提及%s 没有最大字段宽度的危险。
    • 我不得不说这有点令人费解,因为对于任何Type arr[N]arr&amp;arr 的值都是相等的,只要你在arr 的声明。所以要么编译器在这里发出一个无用的警告,要么board[i].name&amp;board[i].name 的值不相同,因为它们没有在声明的“原始”范围内使用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-27
    • 1970-01-01
    • 1970-01-01
    • 2013-10-25
    相关资源
    最近更新 更多