Array of C structs

后端 未结 4 1624
面向向阳花
面向向阳花 2021-01-16 10:54

If I create a struct in C and want to add them to an array that is not set to a fixed size, how is the array created?

Can one create a tempStruct which is used on ev

4条回答
  •  失恋的感觉
    2021-01-16 11:30

    When the size is unknown at compile time, you'll need to allocate the memory on the heap, rather than in the data segment (where global variables are stored) or on the stack (where function parameters and local variables are stored). In C, you can do this by calling functions like malloc.

    MyStructType *myArray = (MyStructType *)malloc(numElements * sizeof(MyStructType)
    ... do something ...
    free(myArray)
    

    If you're actully using C++, it's generally better to use new[] and delete[], e.g.

    MyStructType *myArray = new MyStructType[numElements]
    ... do something ...
    delete [] myArray
    

    Note that new[] must be paired with delete[]. If you're allocating a single instance, use new and delete (without "[]"). delete[] and delete are not equivalent.

    Also, if you're using C++, it's generally easier and safer to use an STL vector.

提交回复
热议问题