c - 将数据存储在头文件中包含数组的 Stucts 中

标签 c arrays function struct header-files

我目前正在尝试将从函数输入的信息存储到我的头文件中声明的结构中,并在主文件中使用它。我不能使用结构数组,因为我不允许分配内存。

头文件

#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 循环确定数组中的位置可能无效,但我现在并不担心。

My question is how do I store the data from this function to the header file?

更新

我更改了 main 函数以适应其他所有功能,但现在我遇到了这个错误。

a label can only be part of a statement and a declaration is not a statement

main中的代码是:

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();

最佳答案

  1. 更改 NewCourse 以返回一个 Course

    Course NewCourse(void);
    
  2. 将实现更改为:

    Course NewCourse()
    {
       int i;
       int CNumber = 0;
    
       Course storeC;
    
       ...
    
       return storeC;
    }
    
  3. 相应地更改 main

    int main()
    {
        Course c = NewCourse();
    }
    

附言

你说,

I cannot use struct arrays because I am not allowed to allocate memory.

我假设这意味着您不能使用动态内存分配。如果您被允许在堆栈中创建一个 struct 数组,您可以使用以下方法简化您的代码:

typedef struct
{
   int CourseID[25];
   char CourseName[100];
}Course;

void NewCourse(Course course[]);

main 中,使用:

Course courses[25];
NewCourse(courses)

响应您的更新

您需要在代码周围添加范围 block { },如下所示:

int main()
{
    {
       Course c = NewCourse();
    }
}

这应该可以解决您的错误并允许您的代码编译。

关于c - 将数据存储在头文件中包含数组的 Stucts 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32676038/

相关文章:

c - 在内存中发现程序的图像

javascript: 这个语法是什么意思?

javascript - JavaScript ecma6 中的对象引用

ios - 在 swift 2.0 中解析 JSON 时出错

php更改url的数组格式

r - 用ggplot中的函数定义的两条线之间的阴影区域

c - 运行程序时出错 - C

c - gfortran debugging with gdb : w_powf. c: 没有那个文件或目录

c - 如何将MPU6050设备数据发送到IoT Hub

我们可以使用 realloc 释放动态分配的内存吗?