【问题标题】:How do i make this into a struct?我如何把它变成一个结构?
【发布时间】:2014-03-21 04:10:45
【问题描述】:

好的,所以我已经删除了试图将其变成结构的所有内容,因为我把它搞砸了。

我需要这个数组代码成为一个结构。

FILE *pFile;
    int choice = 0;
    char buf[40];


    int id[sizeof(buf)];
    char name[sizeof(buf)][20];
    char state[sizeof(buf)][5];
    char dis_code[sizeof(buf)];
    float balance[sizeof(buf)];
    char due_date[sizeof(buf)][40];

这是我到目前为止所做的,但是当我尝试使用它时它会发疯。我仍然不知道如何将文件加载到其中。

struct fileinfo
{
    int id[10];
    char name[20];
    char state[5];
    char dis_code[5];
    float balance[10];
    char due_date[40];
} info[sizeof(buf)];

我错过了什么还是我有正确的想法。问题是当我运行这个时,为什么我会遇到错误的常规数组。

【问题讨论】:

  • 你得到了什么错误?(或者我们应该猜到?)
  • 我主要是在问我是否构建了正确的结构。
  • 或者什么是使该数组成为结构的正确方法。因为我认为这是我的问题

标签: c arrays struct multidimensional-array


【解决方案1】:

我不确定这是否是您唯一的问题,但您已经更改了几个字段的类型。

int id[sizeof(buf)];        // id[i] is an int
char dis_code[sizeof(buf)]; // dis_code[i] is a char
float balance[sizeof(buf)]; // balance[i] is a float

struct fileinfo
{
    int id[10];             // info[i].id is an _array of 10 ints_
    char dis_code[5];       // info[i].dis_code is an _array of 5 chars_
    float balance[10];      // info[i].balance is an _array of 10 floats_
} info[sizeof(buf)];

一个类型的数组和该类型的单个实例的行为将完全不同。

我建议使结构的字段与原始数组元素的类型相同,即:

struct fileinfo
{
    int id;
    char dis_code;
    float balance;
}

【讨论】:

  • 我会试一试
【解决方案2】:

既然你声明了char buf[40] ==> sizeof(buf) = 40。您正在将二维数组更改为一维数组。结构应该是这样的

   struct fileinfo
   {             
     int id[40];
     char name[40][20];
     char state[40][5];
     char dis_code[40];
     float balance[40];
     char due_date[40][40];
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-04
    • 2017-07-01
    • 1970-01-01
    • 2018-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多