OOP

how to create an integer array dynamically?
Can you please be more specific?? Also intergers cant become arrays
Also OOP is not the correct title ;)
> how to create an integer array dynamically?

See: https://cal-linux.com/tutorials//vectors.html
I think this is what you're looking for:

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <new>

int main()
{
    int size = 5;
    int *arr = new int[size]; //dynamically allocating memory for your array of ints

    // The rest of the code
    delete[] arr;
    return 0;
}


EDIT: Yup, I had forgotten to use delete[]. Added it in the code. Whenever you dynamically allocate anything, you must always deallocate it in the end when you don't need it anymore.
Last edited on
Except you never use delete, once again showing why you should be using a vector, or at the very least a smart pointer.
closed account (48T7M4Gy)
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <new>

int main()
{
    int size = 5;
    int *arr = new int[size]; //dynamically allocating memory for your array of ints

    // The rest of the code

    delete[] arr;
    return 0;
}
For completeness, the "objects":

The "vector" object:
1
2
3
4
5
6
7
8
#include <vector>
int main()
{
    int size = 5;
    std::vector<int> arr (size); // object that manages an array of ints
    // The rest of the code
    return 0;
}

The "smart pointer" object:
1
2
3
4
5
6
7
8
#include <memory>
int main()
{
    int size = 5;
    auto arr = std::make_unique<int[]>(size); // object that manages an array of ints
    // The rest of the code
    return 0;
}


Edit: initialization syntax
Last edited on
1
2
3
4
5
int size = 5;

std::vector<int> arr {size}; // creates a sequence of size 1 [5]

std::vector<int> arr2(size); //  creates a sequence of  size 5 [ 0 0 0 0 0 ] 
Topic archived. No new replies allowed.