Search code examples
c++arraysdynamic-arrays

how to initialise and assign vlaue element by element to array dynamically


I want to assign values to a dynamic array element by element in C++. I use the code below to assign values

int *missedlst;
for(int i=0;i<10;i++){
missedlst = new int;
missedlst[i] = i;
}

If I print the values, only the last one is correctly shown. The remaining values are not: the program shows some garbage value. Please help me in assigning the values element by element in a loop.


Solution

  • You're code is doing exactly what you tell it to

    int *missedlst;          // New pointer
    for(int i=0;i<10;i++){   // Loop 10 times
        missedlst = new int; // Change what the pointer points to
        missedlst[i] = i;    // This makes no sense, you don't have an array
    }
    

    What you want is to create a new integer array, and then assign the values.

    int size = 10;                   // A size that is easily changed.
    int* missedList = new int[size]; // New array of size size
    for(int i = 0; i < size; ++i){   // loop size times
        missedList[i] = i;           // Assign the values
    }
    
    // Do stuff with your missedList
    
    // Delete the object.
    delete[] missedList;