gpt4 book ai didi

c - Typedef 结构并传递给函数

转载 作者:太空宇宙 更新时间:2023-11-04 04:34:19 26 4
gpt4 key购买 nike

我正在尝试声明一个 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]

任何帮助将不胜感激

最佳答案

你正在将一个数组传递给一个需要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,但它毕竟可能有用。

关于c - Typedef 结构并传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32790936/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com