0
votes

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.

1
Could you post the error?Rémi Benoit
works for me when i compile it with gcc 4.8.1, maybe there is some other code you are not showing? headers #include stdio.h inttypes.h malloc.h ?AndersK
scanf("%d", &size);. Don't know if it's the problem, but you should npt use "%d" for size_t datatype. See viva64.com/en/k/0023.Greg Prisament

1 Answers

-1
votes

What is the error?

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