How can I create a dynamically sized array of structs?

后端 未结 10 1201
春和景丽
春和景丽 2020-11-27 11:46

I know how to create an array of structs but with a predefined size. However is there a way to create a dynamic array of structs such that the array could get bigger?

<
10条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-27 12:41

    Your code in the last update should not compile, much less run. You're passing &x to LoadData. &x has the type of **words, but LoadData expects words* . Of course it crashes when you call realloc on a pointer that's pointing into stack.

    The way to fix it is to change LoadData to accept words** . Thi sway, you can actually modify the pointer in main(). For example, realloc call would look like

    *x = (words*) realloc(*x, sizeof(words)*2);
    

    It's the same principlae as in "num" being int* rather than int.

    Besides this, you need to really figure out how the strings in words ere stored. Assigning a const string to char * (as in str2 = "marley\0") is permitted, but it's rarely the right solution, even in C.

    Another point: non need to have "marley\0" unless you really need two 0s at the end of string. Compiler adds 0 tho the end of every string literal.

提交回复
热议问题