I’m trying to create a 2d dynamic array using the values of an array of int as my pointers. I don’t know how to put this in words exactly, so here is the code. Maybe you’ll understand what I’m trying to do if you see it.
#include "stdafx.h"
#include <iostream>
using namespace std;
int main(){
const int length =5;
int arr[5]={1,1,3,9,1};
int* AR[length];
for (int i=0; i<length;i++) {
for (int j=0; j<(arr[i]); j++){
AR[i] = new int (arr[i]);
AR[i][j]=93;
cout<<"["<<AR[i][j]<<"] ";
}
cout<<endl;
}
for (int i = 0; i < length; i++) {
for (int j=0; j<arr[i]; j++) {
delete[] AR[i];
delete []&AR;
}
}
return 0;
}
Whenever I run it with arr[] < 4 it runs perfectly, but if the size of arr exceeds 4 values it crashes. Can you see why?
I had this problem too:
or
Explanation:
Creates an integer, set its to 5, and returns a pointer to it.
This allocates space for 5 integers, and returns a pointer to the first.
EDIT: Also your deletes need to be adjusted
EDIT 2: As Wug points out, you have a memory leak as well. Your code will work for now, but every “j” iteration, you allocate new memory for the dynamic array essentially losing access to your previously allocated dynamic single dimension array.
Here’s a super awesome website for learning dynamic memory allocation:
http://www.cplusplus.com/doc/tutorial/dynamic/