Static array vs. dynamic array in C++

后端 未结 11 1646
遥遥无期
遥遥无期 2020-11-22 10:43

What is the difference between a static array and a dynamic array in C++?

I have to do an assignment for my class and it says not to use static arrays, only dynamic

11条回答
  •  故里飘歌
    2020-11-22 11:12

    I think the semantics being used in your class are confusing. What's probably meant by 'static' is simply "constant size", and what's probably meant by "dynamic" is "variable size". In that case then, a constant size array might look like this:

    int x[10];
    

    and a "dynamic" one would just be any kind of structure that allows for the underlying storage to be increased or decreased at runtime. Most of the time, the std::vector class from the C++ standard library will suffice. Use it like this:

    std::vector x(10); // this starts with 10 elements, but the vector can be resized.
    

    std::vector has operator[] defined, so you can use it with the same semantics as an array.

提交回复
热议问题