Can't set variable length with variable

前端 未结 5 1223
梦如初夏
梦如初夏 2021-01-14 14:40

What I\'m trying to do right now is to create an array with a length that is defined by a variable. However, when I put the variable in the array length, it gives me a \"Va

5条回答
  •  清酒与你
    2021-01-14 14:52

    See this question Is there a way to initialize an array with non-constant variables? (C++)

    Short answer is no you cannot directly do this. However you can get the same effect with something like

    int arraySize = 10;
    int * myArray = new int[arraySize];
    

    Now myArray is a pointer to the array and you can access it like an array like myArray[0], etc.

    You can also use a vector which will allow you to have a variable length array. My example allows you to create an array with a variable initailizer however myArray will be only 10 items long in my example. If you aren't sure how long the array will ever be use a vector and you can push and pop items off it.

    Also keep in mind with my example that since you've dyanmically allocated memory you will need to free that memory when you are done with the array by doing something like

    delete[] myArray;
    

    Here is a little sample app to illustrate the point

    #include 
    using namespace std;
    
    
    int _tmain(int argc, _TCHAR* argv[])
    {
        int arraySize = 10;
        int * myArray = new int[arraySize];
        myArray[0] = 1;
        cout << myArray[0] << endl;
    
        delete[] myArray;
    }
    

提交回复
热议问题