Home > Software design >  What would new int[3] do to the int pointer?
What would new int[3] do to the int pointer?

Time:09-22

I was looking for uses for pointers and this turned out to be one of them. Dynamically allocating memmory. I am a little confused with the keyword new, and when adding [number] in the end. new int[3]. I do understand that this question might be bad. I'm only 13.

   #include <iostream>
    using namespace std;
    int main() {
        int* scores;
        cout << "Enter top 3 scores: ";
    
        //dynamically allocate memory
        scores = new int[3];
        for (int i = 0; i < 3; i  ) {
            "Enter score: ";
            cin >> scores[i];
        }
        cout << endl << "Scores are: ";
        for (int i = 0; i < 3; i  ) {
            cout << scores[i] << " ";
        }
        delete[] scores;
    
        return 0;
    }

CodePudding user response:

When you create an integer pointer, you create a memory that contains the address of another memory. So, when you use the keyword 'new' you are allocating memory and its address is then stored in that pointer. Initially, without any allocation, there is no data stored in that integer pointer.

This is similar to what it means when you do int array[size], however, at times dynamically allocated memory is required e.g. if you need to change the size of an array. If you declared an array without dynamic allocation, you can not change its size but when the help of dynamic memory allocation you can easily delete the previously allocated memory and allocate another memory that is larger. A basic example of where dynamic memory ('new' keyword) is used is when you create an array of the names of students in a class, initially, they might be just 15 students but after a month if they grow over 30 and the array you declared was of size 15 you can just use the 'delete' and 'new' keyword to increase the size.

CodePudding user response:

A pointer is basically a variable pointing to a specific address in memory. An array is a group of variables allocated consecutively in memory. When you write scores = new int[3] you allocate a memory for three int-type variables and make the scores variable reference the first one's address. Now, when referencing the array fields: scores[i], you take the address of the first field of the array and you add the variable i, giving you the address of the ith element.

  • Related