因此,我现在正在尝试学习C,还有一些基本的结构性问题需要解决:

基本上,所有内容都围绕以下代码段:

#include <stdio.h>
#include <stdlib.h>

#define MAX_NAME_LEN 127

const char* getName(const Student* s);
void setName(Student* s, const char* name);
unsigned long getStudentID(const Student* s);
void setStudentID(Student* s, unsigned long sid);

int main(void) {
    Student sarah;
    const char* my_name = "Sarah Spond";
    setName(&sarah, my_name);
    printf("Name is set to %s\n", sarah.name);
}

typedef struct {
    char name[MAX_NAME_LEN + 1];
    unsigned long sid;
} Student;

/* return the name of student s */
const char* getName (const Student* s) { // the parameter 's' is a pointer to a Student struct
    return s->name; // returns the 'name' member of a Student struct
}

/* set the name of student s
If name is too long, cut off characters after the maximum number of characters allowed.
*/
void setName(Student* s, const char* name) { // 's' is a pointer to a Student struct |     'name' is a pointer to the first element of a char array (repres. a string)
    int iStringLength = strlen(name);
    for (i = 0; i < iStringLength && i < MAX_NAME_LEN; i++) {
        s->name[i] = name[i];
}
}

/* return the SID of student s */
unsigned long getStudentID(const Student* s) { // 's' is a pointer to a Student struct
    return s->sid;
}

/* set the SID of student s */
void setStudentID(Student* s, unsigned long sid) { // 's' is a pointer to a Student struct | 'sid' is a 'long' representing the desired SID
    s->sid = sid;
}


但是,当我尝试编译该程序时,出现一堆错误,提示存在一个“未知类型名称Student”。我究竟做错了什么?

谢谢!

最佳答案

Student的类型定义-typedef ..移动到#define MAX_NAME_LEN 127之后,即在被引用之前。

08-16 02:31