dynamically change the size of an array c++

后端 未结 3 1014
逝去的感伤
逝去的感伤 2021-01-24 13:56

I have an array defined as;

static double Temp_data[TABLE_SIZE];

I want to change the size of the array according to the user input.

相关标签:
3条回答
  • 2021-01-24 14:16

    Use dynamic memory allocation.

    int size;
    cin>>size
    int *ptr = new int[size];
    

    http://www.cplusplus.com/doc/tutorial/dynamic/

    0 讨论(0)
  • 2021-01-24 14:22

    No. You probably want to use std::vector<double> Temp_data;

    Then you can use its resize() member function to set the size as you see fit.

    Edit: just to be clear, you generally want to avoid using new directly if you can (and in this case, you can very easily). Direct use of new is a constant source of bugs of quite a few types. std::vector handles quite a few corner cases that are difficult to get correct with new, ensures that the data gets cleaned up when it goes out of scope, etc.

    I've said before, and I'll repeat here: at one time, you had little choice but to write code that used new. Now, you do have a choice -- and you should exercise it. Given a modern compiler and standard library, there's almost never any reason to allocate an array with new.

    0 讨论(0)
  • 2021-01-24 14:24

    T *pData

    pData = new T[NUM_ELEMENTS];

    Basically using the new operator. Read more about new from any C++ reference

    0 讨论(0)
提交回复
热议问题