我有一个结构“课程”和一个功能:
typedef struct Course_s
{
char* name;
int grade;
} Course;
int courseGetGrade(Course const* course)
{
assert(course);
return course -> grade;
}
和另一个结构“transcript”和一个函数:
typedef struct Transcript_s
{
char* name;
struct Course** courseArray;
} Transcript;
double tsAverageGrade(Transcript const *t)
{
double temp = 0;
int a = 0;
while(t -> courseArray[a] != NULL)
{
temp = temp + courseGetGrade(t -> courseArray[a]);
a++;
}
return (temp / a);
}
但我似乎无法通过论证t - > courseArray [a]到函数courseGetGrade。我对指针有点困惑,应该如何实现,我只是不明白为什么它不会像现在这样工作。 courseArray是一个Course结构数组,在数组的末尾有一个NULL指针。
我收到警告“从不兼容的指针类型”传递“courseGetGrade”的参数1。如果我在参数之前尝试添加“const”,则警告会更改为错误:“const”之前的预期表达式。
我正在使用普通的C.
非常感谢所有帮助!
编辑。这是完整的编译器输出。完整输出中有更多功能,因此警告比我最初发布的代码更多:
transcript.c: In function âtsAverageGradeâ:
transcript.c:66: warning: passing argument 1 of âcourseGetGradeâ from incompatible pointer type
course.h:27: note: expected âconst struct Course *â but argument is of type âstruct Course *â
transcript.c: In function âtsSetCourseArrayâ:
transcript.c:89: error: invalid application of âsizeofâ to incomplete type âstruct Courseâ
transcript.c:94: warning: assignment from incompatible pointer type
transcript.c: In function âtsPrintâ:
transcript.c:114: warning: passing argument 1 of âcourseGetNameâ from incompatible pointer type
course.h:24: note: expected âconst struct Course *â but argument is of type âstruct Course *â
transcript.c:114: warning: passing argument 1 of âcourseGetGradeâ from incompatible pointer type
course.h:27: note: expected âconst struct Course *â but argument is of type âstruct Course *â
transcript.c: In function âtsCopyâ:
transcript.c:126: warning: passing argument 2 of âtsSetCourseArrayâ from incompatible pointer type
transcript.c:80: note: expected âstruct Course **â but argument is of type âstruct Course ** constâ
Edit.2以下是导致第89行错误的函数:
void tsSetCourseArray(Transcrpt *t, Course **courses)
{
assert(t && courses);
free(t -> courseArray);
int a = 0;
while(courses[a] != NULL)
a++;
t -> courseArray = malloc(sizeof(struct Course) * (a+1));
a = 0;
while(courses[a] != NULL)
{
t -> courseArray[a] = courseConstruct(courseGetName(courses[a]), courseGetGrade(courses[a]));
a++;
}
t -> courseArray[a] = NULL;
}
答案 0 :(得分:2)
变化:
typedef struct Transcript_s
{
char* name;
struct Course** courseArray;
} Transcript;
为:
typedef struct Transcript_s
{
char* name;
Course** courseArray; /* 'Course' is a typedef for 'struct Course_s'. */
} Transcript;
以下是不正确的,原因有两个:
t -> courseArray = malloc(sizeof(struct Course) * (a+1));
struct Course
应该是Course
,但更重要的是它应该是Course*
,因为需要为Course*
分配空间:t->courseArray
是{{1} }}。改为:
Course**
此外,以下内容不会释放t -> courseArray = malloc(sizeof(Course*) * (a+1));
中的Course
个实例,它只释放指针数组:
courseArray
你需要迭代free(t -> courseArray);
并释放每个单独的元素,然后释放指针数组:
courseArray