将数据存储在包含数组的文件中在头文件中
我目前正试图将从函数输入的信息存储到我的头文件中声明的结构中,并在主文件中使用它。我不能使用结构数组,因为我不允许分配内存。将数据存储在包含数组的文件中在头文件中
头文件
#ifndef HOMEWORK_H_
#define HOMEWORK_H_
typedef struct
{
int CourseID[25];
char CourseName[100][25];
}Course;
void NewCourse(void);
#endif
我的代码
#include <stdio.h>
#include <stdlib.h>
#include "Homework.h"
void NewCourse()
{
int i;
int CNumber = 0;
Course storeC;
for(i = 0; i < 0; i++)
{
if(storeC.CourseID[i] == 0)
{
if(storeC.CourseName[i] == NULL)
{
int CNumber = i;
break;
}
}
}
printf("%d\n", CNumber);
printf("Please enter the course's ID number: ");
scanf("%d", &storeC.CourseID[CNumber]);
printf("Please enter the course's name: ");
scanf("%s", storeC.CourseName[CNumber]);
}
和我的主并不真正适用,因为问题的关键在于内存储的数据。
需要注意的一点是我必须为我的函数使用单独的文件,并且我必须为我的结构使用头文件。
我知道我的for循环来确定数组中哪个地方可能无效,但我现在并不担心它。
我的问题是如何将数据从这个函数存储到 头文件?
更新
我改变了主要功能,以适应一切,我现在结束了这个错误。
标号只能是语句的一部分,而声明并非 声明
在主要的代码是:
switch(Option)
{
case 1:
Course c = NewCourse();
printf("%d\n%s\n", c.CourseID[0], c.CourseName[0]); // For testing purposes
break;
是什么原因造成的错误,因为它说它源于第29行,即Course c = NewCourse();
?
-
更改
NewCourse
返回Course
。Course NewCourse(void);
-
更改实施:
Course NewCourse() { int i; int CNumber = 0; Course storeC; ... return storeC; }
-
变化
main
相应。int main() { Course c = NewCourse(); }
PS
你说,
我不能使用结构数组,因为我不能分配内存。
我认为这意味着你不能使用动态内存分配。如果你被允许在堆栈中创建的struct
秒的数组,你可以使用简化代码:
typedef struct
{
int CourseID[25];
char CourseName[100];
}Course;
void NewCourse(Course course[]);
和main
,使用方法:
Course courses[25];
NewCourse(courses)
在回答您的更新
您需要添加一个范围块{ }
周围的代码如下:
int main()
{
{
Course c = NewCourse();
}
}
这应该解决您的错误并允许您的代码进行编译。
此外,您在操作CNumber变量时出错。它被声明两次,用不同的范围:
int CNumber = 0;
//使用NewCourse功能
然后将试验内的范围的第一个定义,与块范围:
if(storeC.CourseID[i] == 0)
{
if(storeC.CourseName[i] == NULL)
{
int CNumber = i; // block-scope. This is not the same CNumber Variable (todo: Omit int)
break;
}
}
结果,稍后参考它时
printf("%d\n", CNumber);
printf("Please enter the course's ID number: ");
scanf("%d", &storeC.CourseID[CNumber]);
printf("Please enter the course's name: ");
scanf("%s", storeC.CourseName[CNumber]);
它总是引用函数作用域变量,它始终为零。
解决方法:省略int类型声明的测试内:
if(storeC.CourseName[i] == NULL)
{
CNumber = i;
break;
}
非常感谢。我真的在CNumber之前忘记了那个int。我甚至不知道为什么我把它包括在内,但是非常感谢你的支持。 – Arrowkill
欢迎。很高兴帮助。 –
“不允许分配内存”。你意识到堆栈是分配的内存区域,对吧? – CoffeeandCode
我的意思是使用Malloc或Calloc – Arrowkill
然后你的意思是你不允许动态分配任何内存。 – CoffeeandCode