Everything is fine except one line. In void menuSwitch(int* courseNum, struct courseData** course)
change
addCourse(&courseNum, course)
to
addCourse(courseNum, course);
题
I am having problems passing a pointer to a pointer(struct) through a nested function to have memory allocated or reallocated for it. I understand that when passing to a function it is passed by value, and thus only can be edited locally, but am unclear syntactically how to pass it. Important code snippets below:
struct courseData{
char name[25];
int id;
};
void menuSwitch(int* courseNum, struct courseData** course);
void addCourse(int* courseNum, struct courseData** course);
int main(){
struct courseData* course = NULL;
int courseNum = 0;
menuSwitch(courseNum, &course); //Edited from original post.
return 0;
}
void menuSwitch(int* courseNum, struct courseData** course){
addCourse(&courseNum, course)
}
menuSwitch is actually a case switch, which calls function addCourse when the menu item is selected.
void addCourse(int* courseNum, struct courseData** course){
if(*courseNum == 0)
*course = (struct courseData*) malloc(sizeof(struct courseData));
else
*course = (struct courseData*) realloc(*course, (*courseNum + 1)*sizeof(struct courseData));
*courseNum = *courseNum + 1; //Increments course count by 1
------code continues------
}
After correcting original problem, compiling results in the following errors/warnings from gcc
main.c: In function ‘main’:
main.c:27:3: warning: passing argument 2 of ‘menuSwitch’ from incompatible pointer type [enabled by default]
header.h:24:6: note: expected ‘struct courseData *’ but argument is of type ‘struct courseData **’
func.c:60:6: error: conflicting types for ‘menuSwitch’
header.h:24:6: note: previous declaration of ‘menuSwitch’ was here
func.c: In function ‘menuSwitch’:
func.c:64:3: warning: passing argument 2 of ‘addCourse’ from incompatible pointer type [enabled by default]
header.h:26:6: note: expected ‘struct courseData *’ but argument is of type ‘struct courseData **’
Thank you for your help, and pardon if this is inappropriate use of the edit ability.
解决方案
Everything is fine except one line. In void menuSwitch(int* courseNum, struct courseData** course)
change
addCourse(&courseNum, course)
to
addCourse(courseNum, course);
其他提示
You were doing fine until you got to menuSwitch
. That function receives courseNum
, which is a pointer to int
. It should then pass that same pointer addCourse
just as it does with course
. However, you pass the address of courseNum
instead. So instead of passing an int *
you're passing the address of a pointer to int *
, or an int **
. The call to addCourse
should simply be this:
addCourse(courseNum, course);