The code writes 2d arrays using different methods and although is working as expected i want to know if im doing some extra coding (mainly i have doubts with: arr2=new int*[4];). |
Any time you are manually using new[] you are doing extra coding. Container classes exist so you do not have to manually allocate/free memory like this. IE instead of using an array that you allocate with new[], you could just use a vector.
That said:
int arr[][2]={{w,x},{y,z}};
Storage:
- Memory is stored congruently. IE, this is simply stored as {w,x,y,z}
Pros:
- On stack, so it will be automatically cleaned up
- Simple allocation and initialization
- Congruent memory means no pointer indirection which means it's ever-so-slightly-faster.
Cons:
- On stack, so cannot have extraordinarily large arrays or you'll exhaust stack space
- Must have fixed array dimensions. Cannot size array dynamically.
int (*arr1)[2]=new int[2][2];
Storage:
- Not congruent. Outer array stored as {ptr1,ptr2} with two other arrays stored separately as {w,x} and {y,z}
Pros:
- Bulk of data stored on the heap, so you can have fairly large arrays.
- Non-congruent memory means it can be fragmented which means less chance of allocation failure.
Cons:
- Inner array size is fixed. Cannot be changed dynamically
- Potential for memory leak if you forget to
delete[] arr1;
- Not as easy to initialize data
int **arr2;
Storage:
- Not congruent at all. arr2 is a single pointer stored as {arr2}, with it pointing to another array of pointers stored as {ptr1,ptr2}, each of which pointing to an array stored as {w,x} and {y,z}.
Pros:
- All data except for a single pointer stored on heap. Arrays can be freaking huge.
- Non congruent memory means it can be fragmented. Less chance of allocation failure
- Both dims are dynamic
Cons:
- Allocation is a disaster. The initial new[] plus another set of new[]s in a loop
- Cleanup is equally disasterous. A set of delete[]s in a loop, followed by the outer delete[]. High risk of memory leak if not done properly.
- Double indirection means CPU has to follow two sets of pointers to reach actual data... which is the slowest of all mentioned options so far.
vector<vector<int>> vec(2,2) = {{w,x},{y,z}};
Storage:
- Same as arr2
Pros:
- All pros of arr2
- Simple allocation and initialization
- Automatic cleanup, no risk of memory leak.
Cons:
- Double indirection, same as arr2. Not the fastest.
- Vector might allocate more memory than you actually need in anticipation of the array growing. It's possible this might use more memory than other approaches.
Overall there is little if any reason to favor natural arrays over a vector... vectors are pretty much just better. If speed is that much of a concern, you can mimic a 2D array by using a 1D vector and just doing some math before accessing elements, as I illustrate with the 'Array2D' class in this thread:
http://www.cplusplus.com/forum/articles/17108/#msg85595