c - 如何创建结构数组

标签 c arrays pointers struct

我想实现一个搜索表并且 这是数据:

20130610    Diamond CoinMate    11.7246 15.7762 2897
20130412    Diamond Bithumb     0.209   0.2293  6128
20130610    OKCash  Bithumb     0.183   0.2345  2096
20130412    Ethereum    Chbtc   331.7282    401.486 136786
20170610    OKCash  Tidex       0.0459  0.0519  66
...

和我的代码

typedef struct data{
    int *date;
    string currency[100];
    string exchange[100];
    double *low;
    double *high;
    int *daily_cap;
} Data;

int main()
{
    FILE *fp = fopen("test_data.txt", "r");
    Data tmp[50];
    int i = 0;
    while (!feof(fp)){
        fscanf(fp, "%d%s%s%f%f%7d", &tmp[i].date, tmp[i].currency, tmp[i].exchange, &tmp[i].low, &tmp[i].high, &tmp[i].daily_cap);
        i++;
    }
    fclose(fp);
}

但第一个问题是我无法创建一个大数组来存储我的结构

Data tmp[1000000]

甚至我只尝试了 50 个元素,程序在完成 main() 时崩溃了。 谁能告诉我如何修复它或给我一个更好的方法,谢谢。

最佳答案

你不能扫描一个值到未分配的空间,换句话说,你需要为 struct 中的所有指针留出空间,切换到

typedef struct data{
    int date;
    string currency[100];
    string exchange[100];
    double low;
    double high;
    int daily_cap;
} Data;

或者使用 malloc 在使用它们之前为这些指针分配空间。

while (!feof(fp)){
   tmp[i].date = malloc(sizeof(int));
   ...

但在这种情况下,您不需要将此类成员的地址传递给 fscanf,因为它们已经是指针:

fscanf(fp, "%d%s%s%f%f%7d", &tmp[i].date, ..

应该是

fscanf(fp, "%d%s%s%lf%lf%7d", tmp[i].date, ...

注意 double 需要 %lf 而不是 %f

这也很困惑:

typedef struct data{
    int *date;
    string currency[100];
    ...

stringchartypedef 吗?我想你的意思是 string currency; 因为 string 通常是 char * 的别名,在这种情况下你也需要这个成员的空间:货币 = malloc(100);

最后看看Why is “while ( !feof (file) )” always wrong?

一小段错误太多,建议你看一本不错的C书。

您的代码已使用动态内存更正,允许您为大量数据保留空间(请参阅@LuisColorado 的其他答案)并改用 fgetssscanf fscanf 的:

#include <stdio.h>
#include <stdlib.h>

typedef struct data{
    int date;
    char currency[100];
    char exchange[100];
    double low;
    double high;
    int daily_cap;
} Data;

int main(void)
{
    FILE *fp = fopen("test_data.txt", "r");
    /* Always check the result of fopen */
    if (fp == NULL) {
        perror("fopen");
        exit(EXIT_FAILURE);
    }

    Data *tmp;
    tmp = malloc(sizeof(*tmp) * 50);
    if (tmp == NULL) {
        perror("malloc");
        exit(EXIT_FAILURE);
    }

    char buf[512];
    int i = 0;
    /* Check that you don't read more than 50 lines */
    while ((i < 50) && (fgets(buf, sizeof buf, fp))) {
        sscanf(buf, "%d%99s%99s%lf%lf%7d", &tmp[i].date, tmp[i].currency, tmp[i].exchange, &tmp[i].low, &tmp[i].high, &tmp[i].daily_cap);
        i++;
    }
    fclose(fp);
    /* Always clean what you use */
    free(tmp);
    return 0;
}

关于c - 如何创建结构数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49606737/

相关文章:

C memcpy 二维数组

c - 从数组中打印随机选择

c - 具有较大固定长度且填充为零的 mmap 文件?

c - 如何在数组中存储 1 000 000 000 个项目?

c - 输入字符串的动态分配

c++ - 从原始指针创建 weak_ptr<>

c - 为什么 fun(int *p) 不改变指针的值?

arrays - 在 MATLAB 中将整数转换为逻辑数组

JavaScript : after calling the splice() control comes out from the loop

c++ - 无法从指针访问映射成员