Why is this crashing both CodeBlocks and VisualStudio?

Aug 16, 2015 at 5:25pm
It keeps giving me a runtime error.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include<iostream>
#include<vector>
#include<string>
#include <cstring>

using namespace std;

int main()
{
	int *myArray =NULL; //Declares pointer
	int size;
	cout << "How big is your array?" << endl;
	cin >> size;
	myArray[size];
	for (int index = 0; index < size; index++)
	{
		myArray[index] = index;
		cout << myArray[index] << endl;
	}
	cout << *myArray << endl;
	cout << *(myArray + 2) << endl;


	return 0;
Aug 16, 2015 at 5:32pm
Line 14 is not how you allocate an array. If you want to dynamically allocate an array you should use the new keyword.
 
myArray = new int[size];

If you use new to allocate memory you should also not forget to delete it when you are finished using it.
 
delete[] myArray;

Note that the [] are necessary when deleting arrays.
Aug 16, 2015 at 5:37pm
The solution here is to allocate memory to be able to store these numbers. It looks like your tried this on line 14, but that line should look like myArray = new int[size];. Allso, do not forget to call delete[] myArray; when you are finished using this dynamically allocated memory.
Aug 16, 2015 at 6:01pm
Thank you!
Topic archived. No new replies allowed.