Quick C++ Question...

gopunk

Lifer
Jul 7, 2001
29,239
2
0
if i have a dynamically allocated two dimensional array, will

delete [] myArray;

deallocate it? or do i need [][] or something in there?
 

blahblah99

Platinum Member
Oct 10, 2000
2,689
0
0
i believe its just "delete myArray", or "free myArray",

i dont think you need the brackets.
 

gopunk

Lifer
Jul 7, 2001
29,239
2
0


<< Err.. How does one dynamically allocate a 2 dimensional array? >>



probably a question i should have asked myself before i tried to do it.

i'm using an array of arrays, but you can also just have one long array, so that a 2x2 array would really be a one dimensional array of 4.
 

Ameesh

Lifer
Apr 3, 2001
23,686
1
0


<<

<< Err.. How does one dynamically allocate a 2 dimensional array? >>



probably a question i should have asked myself before i tried to do it.

i'm using an array of arrays, but you can also just have one long array, so that a 2x2 array would really be a one dimensional array of 4.
>>



in memory all arrays are one dimension they use the array forumla to find the right position thats what the [] operators do.

i think the first quote is refering to the fact that when you declare an array with dimension in your code you are declaring it staticlly, but you can create dynamically by creating during runtime.


in any case a simple delte should work if your program scope is the same if say you are handing the pointer to the array to an outside program for example it hink you mighthave to cast it before you delete it.
 

Ameesh

Lifer
Apr 3, 2001
23,686
1
0
sorry you do have to do a delete [] foo

if you didnt and you just said delete foo
where foo is int[1000]


then you would only unallocate the first element of foo


understand why?
 

arcain

Senior member
Oct 9, 1999
932
0
0


<< i'm using an array of arrays, but you can also just have one long array, so that a 2x2 array would really be a one dimensional array of 4. >>



Well.. you have 2 different problems/difficulties with both methods.

With the first, assuming a dynamically allocated array of arrays, which would be a pointer of pointers, in order to delete, you would need to loop through the "outer" array, and delete [] the individual pointers, and then delete[] the "outer" array. I've never tried it personally but I suppose it should work (as I have used it when reading command line arguments I guess.. like char **argv vs char *argv[]).

With the second, you can allocate the a one dimensional array/pointer, but you cannot address it as array[x][y], because the compiler does not know how "wide" the array is.
array[x][y] is the same as *(array+(x*arrayWidth+y)*sizeof(yourType)).
Say you allocated 16 "blocks" for your array. You use it with say array[1][3]. The address that gets calculated will be different (err.. could be because I'm too lazy to work out the math) if the array is 1x16 (buffer overflow in this case), 2x8, or 4x4 (etc.. you get the picture).