简体   繁体   中英

How can I initialize array of structs to global in c?

I want to make struct global I tried something but I got an error.

struct data{
    int barcode;
    char product_name[50];
    char category[50];
    float price;
};

void printer(){
    struct data *data1=(struct data*)malloc(sizeof(struct data));
}

int main()
{
    struct data *data1=(struct data*)malloc(sizeof(struct data));
    return 0;
}

"error:initializer element is not constant"

struct data{
    int barcode;
    char product_name[50];
    char category[50];
    float price;
};
struct data *data1=(struct data*)malloc(sizeof(struct data));

You can't call malloc outside a function context. If you want a single structure, declare it as a global variable. If you want multiple structures, make an array.

struct data data1;
struct data dataN[12];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM