我想聲明一個typedef結構數組,然後將它傳遞給一個函數,但我得到的錯誤,因爲我不完全確定正確的語法,幫助將不勝感激。這裏是我的代碼:Typedef結構並傳遞給函數
#include <stdlib.h>
#include <stdio.h>
#define MAX_COURSES 50
typedef struct courses //creating struct for course info
{
int Course_Count;
int Course_ID;
char Course_Name[40];
}course;
void Add_Course(course , int *);
int main()
{
course cors[MAX_COURSES];
int cors_count = 0;
Add_Course(cors, &cors_count);
return 0;
}
void Add_Course(course cors, int *cors_count)
{
printf("Enter a Course ID: "); //prompting for info
scanf("%d%*c", cors.Course_ID);
printf("Enter the name of the Course: ");
scanf("%s%*c", cors.Course_Name);
cors_count++; //adding to count
printf("%p\n", cors_count);
return;
}
我得到的錯誤是:
error: incompatible type for argument 1 of ‘Add_Course’
test2.c:28:6: note: expected ‘course’ but argument is of type ‘struct course *’
test2.c: In function ‘Add_Course’:
test2.c:81:2: warning: format ‘%d’ expects argument of type ‘int *’, but argument 2 has type ‘int’ [-Wformat]
任何幫助,將不勝感激
對於數組傳遞,C有點奇怪。您必須通過引用傳遞數組。如前所述,你的函數簽名應該是'Add_Course(course * cors,int * cors_count)'。 但是,在訪問* cors_count時,您需要取消引用它。要增加cors_count,你需要執行'* cors_count ++'。在不提取它的情況下,你正在增加指針,而不是計數器。 –