How to use new to allocate space?

I have no idea how to use new or what it means. I would appreciate it if someone can explain it to me in an easy to understand way since I am a beginner.
Last edited on
int *foo = new int [x];

> I just have no idea (...) what it means
¿what?
thanks guys!! :)
closed account (2UD8vCM9)
One way to use new is like using a dynamic array.

So for example, if we have
 
int MyArray[100];


Then we have an array of size 100 that can never be resized. Using new, we could get this effect by doing

 
int * MyArray = new int[100];


However, in this example we could choose the size of our array by changing the number in the brackets. That being said, we could do something like
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
using namespace std;
int main()
{
	int ArraySize;
	cout << "Enter Array Size:";
	cin >> ArraySize;
	int * MyArray = new int[ArraySize]; //This would create an array of size ArraySize
	for (int i = 0; i < ArraySize; i++)
	{
		cout << "Enter an integer:";
		cin >> MyArray[i];
	}
	delete[] MyArray;
	return 0;
}


If you notice, after I was done using MyArray, I called delete[] MyArray;

Every time you use new, you need to use delete when you're done with that memory. If you don't, then you have memory leaks.
Last edited on
If you notice, after I was done using MyArray, I called delete MyArray;
And you just got undefined behavior in your program.

You should never ever use delete for anything allocated with new[], and likewise, never use delete[] for something allocated with new.
Eacch new should be paired with delete and new[] with delete[]
closed account (2UD8vCM9)
Was a typo, but MiiniPaa is correct you should use delete[] with new[] and delete with new.
Topic archived. No new replies allowed.