2015-09-25 87 views
1

我想聲明一個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]

任何幫助,將不勝感激

+0

對於數組傳遞,C有點奇怪。您必須通過引用傳遞數組。如前所述,你的函數簽名應該是'Add_Course(course * cors,int * cors_count)'。 但是,在訪問* cors_count時,您需要取消引用它。要增加cors_count,你需要執行'* cors_count ++'。在不提取它的情況下,你正在增加指針,而不是計數器。 –

回答

0

您將數組傳遞給預期的struct course實例的功能,嘗試像這樣

Add_Course(cors[cors_count], &cors_count); 

但是,它只會被修改在Add_Course所以你需要

void Add_Course(course *cors, int *cors_count) 
{ 
    printf("Enter a Course ID: "); 
    /* this was wrong, pass the address of `Course_ID' */ 
    scanf("%d%*c", &cors->Course_ID); 
    /* Also, check the return value from `scanf' */ 
    printf("Enter the name of the Course: "); 
    scanf("%s%*c", cors->Course_Name); 

    /* You need to dereference the pointer here */ 
    (*cors_count)++; /* it was only incrementing the pointer */ 

    return; 
} 

,現在你可以

for (int index = 0 ; index < MAX_COURSES ; ++index) 
    Add_Course(&cors[index], &cors_count); 

雖然cors_count將等於在這種情況下MAX_COURSES - 1,它migh終究是有用的。

+0

進行您所建議的更改告訴我: 錯誤:「Add_Course」參數1的不兼容類型 注:期望的'struct course *'但參數類型爲'course' 任何想法? – ColinO

+0

是的,你沒做第二部分......'Add_Course(&cors [index],&cors_count);' –

0

在您的Add_Course()函數中,第一個參數的類型爲course,但是您傳遞的是類型爲course的數組,它們並不相同。如果你想傳遞數組,你需要有一個指向course的指針作爲第一個參數。

接下來,scanf("%d%*c", cors.Course_ID);也是錯誤的,scanf()期望格式說明符的參數作爲指向變量的指針。您需要提供變量的地址。另外,printf("%p\n", cors_count);顯然應該是printf("%d\n", *cors_count);

也就是說,cors_count++;可能不是你想要的。你想增加的值,而不是指針本身。