簡體   English   中英

結構中的C malloc

[英]C malloc within a struct

我正在嘗試使用從命令傳遞的3個檔案中讀取的值來分配一個結構。 我有3種類型的硬幣,它們的價格和日期已經變成數組,但不是動態的。 如何從結構中分配這些日期和價格?

命令

a.exe BTC.csv NEO.csv IOT.csv

BTC.csv

253   
02/20/18,11403.7   
02/19/18,11225.3   
02/18/18,10551.8   
02/17/18,11112.7   
02/16/18,10233.9  
 ...

NEO.csv

253    
02/20/18,128.36    
02/19/18,137.47    
02/18/18,127.38    
02/17/18,136.75    
02/16/18,128.85   
...

物聯網

253    
2/20/18,1.91    
2/19/18,2.09    
2/18/18,1.98   
2/17/18,2.2   
2/16/18,2.1   
...

碼:

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

typedef struct
{
    int month;
    int day;
    int year;
    double value;
}array;

typedef struct
    {   //I want allocate these arrays dynamically
    int month[253];
    int day[253];
    int year[253];
    double newvalue[253];
}coin;

int main(int argc, char *argv[]){
    FILE *csv;
    char string[9];
    long int n_lines=0;
    int n = argc-1;

    coin *m = (coin*)malloc(n*sizeof(coin));

    for(int z=1; z<argc; z++)
       {
        sprintf(string, "%s", argv[z]);

        if((csv=fopen(string, "r")) == NULL)
        {
            printf("%s not found\n", string);
            exit(1);
        }

        fscanf(csv, "%li", &n_lines); //n_lines=253

        array *v;
        v=(array*)malloc(n_lines*sizeof(array));

        char line[256];
        int i=0;

        while (fgets(line, 256, csv) != NULL && i<n_lines)
        {
                int count = fscanf(csv, "%d/%d/%d,%lf", &v[i].month, &v[i].day, &v[i].year, &v[i].value);

                m[z-1].month[i] = v[i].month;
                m[z-1].day[i] = v[i].day;
                m[z-1].year[i] = v[i].year;
                m[z-1].newvalue[i] = (v[i].value)/2;
                i++;
        }

        free(v);

        fclose(csv); 

    }

    for(int z=1;i<argc;z++)
    {
        for(int i=0;i<n_lines;i++)
        {
           printf("%0.2d/%0.2d/%0.2d  %lf\n", m[z-1].month[i], m[z-1].day[i], m[z-1].year[i], m[z-1].newvalue[i]);
        }
    }

    return 0;
}

而不是將結構設置為一堆數組:

typedef struct
{   //I want allocate these arrays dynamically
    int month[253];
    int day[253];
    int year[253];
    double newvalue[253];

}coin;

只需使用指針:

typedef struct
{
    int *month;
    int *day;
    int *year;
    double *newvalue;
} coin;

v=(array*)malloc(n_lines*sizeof(array));之后為它們動態分配內存v=(array*)malloc(n_lines*sizeof(array));

coin c;
c.month = malloc(n_lines * sizeof(int));
c.day = malloc(n_lines * sizeof(int));
c.year = malloc(n_lines * sizeof(int));
c.newvalue = malloc(n_lines * sizeof(double));

使用完它們后,不要忘記free()它們。

我認為您應該分配array結構的n數組。 最好將其稱為coin ,或者也許是coin_value (或某種Camel_Case名稱,例如Coin_Value ),但這是基本的輸入類型。 這有點復雜,因為您需要由3個(253)結構的數組組成的數組,但是它比在結構內部隱藏單獨的數組要干凈得多,不僅因為它大大簡化了內存分配(每個文件一個)。 確實,可以一次分配所有內存(並因此一次釋放它),但是我還沒有這樣做。 該代碼也不會檢查數據文件是否都具有相同的行數-應該。 也沒有檢查相應條目中的日期值是否匹配。 再次,可能應該進行這種檢查。 當發現錯誤時,它將報告標准錯誤並退出。

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

typedef struct Coin_Value
{
    int month;
    int day;
    int year;
    double value;
} Coin_Value;

int main(int argc, char *argv[])
{
    FILE *csv;
    long n_lines = 0;
    int n = argc - 1;

    Coin_Value **m = (Coin_Value **)malloc(n * sizeof(*m));
    if (m == 0)
    {
        fprintf(stderr, "Memory allocation failure (%zu bytes)\n", n * sizeof(*m));
        exit(1);
    }

    /* Should check that number of lines in each file is consistent */
    for (int z = 1; z < argc; z++)
    {
        if ((csv = fopen(argv[z], "r")) == NULL)
        {
            fprintf(stderr, "%s not found\n", argv[z]);
            exit(1);
        }

        if (fscanf(csv, "%li", &n_lines) != 1)
        {
            fprintf(stderr, "failed to read a number from %s\n", argv[z]);
            exit(1);
        }
        if (n_lines <= 0 || n_lines > 1000)
        {
            fprintf(stderr, "number of lines in %s out of control (got %ld)\n", argv[z], n_lines);
            exit(1);
        }

        /* Gobble any trailing data and newline */
        int c;
        while ((c = getc(csv)) != EOF && c != '\n')
            ;

        Coin_Value *v = (Coin_Value *)malloc(n_lines * sizeof(*v));
        if (v == 0)
        {
            fprintf(stderr, "Memory allocation failure (%zu bytes)\n", n_lines * sizeof(*v));
            exit(1);
        }

        char line[256];
        for (int i = 0; fgets(line, sizeof(line), csv) != NULL && i < n_lines; i++)
        {
            if (sscanf(line, "%d/%d/%d,%lf", &v[i].month, &v[i].day, &v[i].year, &v[i].value) != 4)
            {
                fprintf(stderr, "Format error processing line: %s", line);
                exit(1);
            }
        }

        m[z-1] = v;

        fclose(csv);
    }

    /* Multi-column output */
    putchar('\n');
    for (int z = 1; z < argc; z++)
        printf("%s%19.3s", (z == 1) ? "" : "   ", argv[z]);
    putchar('\n');

    for (long i = 0; i < n_lines; i++)
    {
        for (int z = 1; z < argc; z++)
        {
            printf("%s%.2d/%.2d/%.2d  %9.2f", (z == 1) ? "" : "   ",
                   m[z - 1][i].month, m[z - 1][i].day, m[z - 1][i].year, m[z - 1][i].value);
        }
        putchar('\n');
    }
    putchar('\n');

    for (int z = 1; z < argc; z++)
    {
        printf("%.3s:\n", argv[z]);
        for (long i = 0; i < n_lines; i++)
        {
            printf("%.2d/%.2d/%.2d  %9.2f\n",
                   m[z - 1][i].month, m[z - 1][i].day, m[z - 1][i].year, m[z - 1][i].value);
        }
        putchar('\n');
    }

    for (int z = 1; z < argc; z++)
        free(m[z-1]);
    free(m);

    return 0;
}

此代碼以兩種不同的方式打印數據:

  1. 在整個頁面的N列中。
  2. 在頁面的N組條目中。

在樣本輸入上(5行而不是253行):

                BTC                   NEO                   IOT
02/20/18   11403.70   02/20/18     128.36   02/20/18       1.91
02/19/18   11225.30   02/19/18     137.47   02/19/18       2.09
02/18/18   10551.80   02/18/18     127.38   02/18/18       1.98
02/17/18   11112.70   02/17/18     136.75   02/17/18       2.20
02/16/18   10233.90   02/16/18     128.85   02/16/18       2.10

BTC:
02/20/18   11403.70
02/19/18   11225.30
02/18/18   10551.80
02/17/18   11112.70
02/16/18   10233.90

NEO:
02/20/18     128.36
02/19/18     137.47
02/18/18     127.38
02/17/18     136.75
02/16/18     128.85

IOT:
02/20/18       1.91
02/19/18       2.09
02/18/18       1.98
02/17/18       2.20
02/16/18       2.10

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM