Resizing an array with C

前端 未结 3 556
后悔当初
后悔当初 2020-11-28 07:26

I need to have an array of structs in a game I\'m making - but I don\'t want to limit the array to a fixed size. I\'m told there is a way to use realloc to make the array bi

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-28 08:14

    Start off by creating the array:

    structName ** sarray = (structName **) malloc(0 * sizeof(structName *));
    

    Always keep track of the size separately:

    size_t sarray_len = 0;
    

    To increase or truncate:

    sarray = (structName **) realloc(sarray, (sarray_len + offset) * sizeof(structName *));
    

    Then set the size:

    sarray_len += offset;
    

    Happy to help and hope that helps.

提交回复
热议问题