Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I don't understand how to create and use dynamic arrays in C++

Tags:

c++

arrays

Okay so I have;

int grid_x = 5
int * grid;
grid = new int[grid_x];
*grid = 34;
cout << grid[0];

Should line 3 create an array with 5 elements? Or fill the first element with the number 5?

Line 4 fills the first element, how do I fill the rest?

Without line 4, line 5 reads "-842150451".

I don't understand what is going on, I'm trying to create a 2 dimensional array using x and y values specified by the user, and then fill each element one by one with numeric values also specified by the user. My above code was an attempt to try it out with a 1 dimensional array first.

like image 785
mrmike Avatar asked Nov 29 '22 11:11

mrmike


1 Answers

The default C++ way of creating a dynamic(ally resizable) array of int is:

std::vector<int> grid;

Don't play around with unsafe pointers and manual dynamic allocation when the standard library already encapsulates this for you.

To create a vector of 5 elements, do this:

std::vector<int> grid(5);

You can then access its individual elements using []:

grid[0] = 34;
grid[1] = 42;

You can add new elements to the back:

// grid.size() is 5
grid.push_back(-42);
// grid.size() now returns 6

Consult reference docs to see all operations available on std::vector.

like image 140
Angew is no longer proud of SO Avatar answered Dec 15 '22 23:12

Angew is no longer proud of SO