我刚开始学C,不知道这里有什么问题。
编辑

#include <stdio.h>

int main (int argc, const char * argv[]) {

struct student {
    int age;
    char gender;
    char course[30];
};

defineNewStudent("Jarryd", 24, 'M', "Software Engineering");

return 0;
}

void defineNewStudent(char studentName[20], int age, char gender, char course[30])
{
student studentName[30];
studentName.age = age;
studentName.gender = gender;
studentName.course = course[20];

printf("%s is %d.\n Gender: %c.\n Course: %s.\n", studentName, studentName.age,  studentName.gender, studentName.course);
}

我有个警告
警告:函数“definewstudent”的隐式声明
我正在尝试接受传入参数并使用它命名结构,这是如何完成的?
这个警告是关于什么的,后果是什么?
谢谢

最佳答案

错误似乎是因为结构student只在函数main中定义您正试图在defineNewStudent函数中使用它,但那里没有定义该结构。在全局范围定义结构。
警告是因为您试图在实际声明之前调用defineNewStudent函数,而编译器仍然不知道这一点在尝试使用函数之前,可以先声明它。

// define the student struct at global scope
struct student
{
    int age;
    char gender;
    char course[20];
};

// declare the function (it can still be defined later)
void defineNewStudent(char studentName[20], int age, char gender, char course[20]);

int main (int argc, const char * argv[])
{
   defineNewStudent("Jarryd", 24, 'M', "Software Engineering");

   return 0;
}

void defineNewStudent(char studentName[20], int age, char gender, char course[20])
{
    // you already have a variable called studentName,
    // you can't have two variables with the same name
    struct student studentData;
    studentData.age = age;
    studentData.gender = gender;
    studentData.course = course;

    printf("%s is %d.\n Gender: %c.\n Course: %s.\n",
         studentName,
         studentData.age,
         studentData.gender,
         studentData.course
    );
}

编辑:
要在C中定义结构的实例,您需要struct关键字,因此在示例中应该是
struct student studentData;
studentData.age = age;
studentData.gender = gender;
studentData.course = course;

如果是c++,则可以删除struct关键字:
student studentData;
studentData.age = age;
studentData.gender = gender;
studentData.course = course;

(可选)在C语言中,您可以将结构定义为别名,以便于定义它的实例:
typedef struct student
{
    int age;
    char gender;
    char course[20];
} StudentStruct;

// define it like this in the function:
StudentStruct studentData;

关于c - 基本的C帮助:函数声明,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4660620/

10-09 08:41
查看更多