0

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.

PlushEngineCell
  • 775
  • 1
  • 7
  • 14

1 Answers1

-1

What is the error?

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

  • 1
    -1 you should never start an answer with a question. Edit: I removed the down-vote since you're new to SO, and probably can't make comments. – tay10r Oct 29 '13 at 06:41
  • But error is not given in question, I am not sure which error Plush asking I suggested on correction. – Gaurav Singal Oct 29 '13 at 07:05
  • 2
    I'd suggest to look up the term "flexible array member", then delete this question/answer. – Lundin Oct 29 '13 at 07:16