PlushEngineCell
PlushEngineCell

Reputation: 825

C. Dynamic Array of Struct

I'd like create dynamic array of struct player. I know size of struct, so i wouldn't like allocate memory for each struct. So i define

struct player
{
    uint32_t efficiency ;
    uint32_t number;
} ;

struct array
{
    size_t   size;
    struct player data[];
};

BUT after I create and fill array and try to read data, I get an error

static inline size_t sizeof_array(size_t size)
{
    return sizeof(struct array) + (size * sizeof(struct player));
}

struct array *create_array(size_t size)
{
    struct array *ret = calloc(1, sizeof_array(size));
    if (! ret)
        abort();
    ret->size = size;
    return ret;
}

void free_array(struct array *array)
{
    free(array);
}

int main()
{
    size_t size;
    scanf("%d",&size);
    struct array *players = create_array(size);

    for(size_t i = 0; i < size; ++i){
        players -> data[i].efficiency = i; //some data
        players -> data[i].number = i;     //some data
    }

    for(size_t i = 0; i < size; ++i){
        printf("%d) %d\n", players -> data[i].number,players -> data[i].efficiency);
    }

    free_array(players);
    return 0;
}

ERROR: This application has requested the Runtime to terminate it in an unusual way. Please contact the application's support team for more information.

How should I allocate memory?

UPDATE headers: stdio.h, stdint.h, inttypes.h, stdlib.h

gcc (rev2, Built by MinGW-builds project) 4.8.0 Copyright (C) 2013 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

Upvotes: 0

Views: 1183

Answers (1)

Gaurav Singal
Gaurav Singal

Reputation: 1

What is the error?

In your struct definition error is struct player data[]; it should be struct player* data; or write data[100]

Upvotes: -1

Related Questions