Typedef结构并传递给函数

问题描述:

我想声明一个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 ++'。在不提取它的情况下,你正在增加指针,而不是计数器。 –

您将数组传递给预期的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);' –

在您的Add_Course()函数中,第一个参数的类型为course,但是您传递的是类型为course的数组,它们并不相同。如果你想传递数组,你需要有一个指向course的指针作为第一个参数。

接下来,scanf("%d%*c", cors.Course_ID);也是错误的,scanf()期望格式说明符的参数作为指向变量的指针。您需要提供变量的地址。另外,printf("%p\n", cors_count);显然应该是printf("%d\n", *cors_count);

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