So, I was giving some examples of how to use dynamically-allocated 2d arrays and was about to send code that was essentially the following:
int size = 5;
int* arr = new int[ size ];
for( int i = 0; i < size; i++ )
arr[ i ] = i;
delete[] arr;
size = 10;
int* arr = new int[ size ];
for( int i = size; i > 0; i-- )
arr[ i ] = i;
delete[] arr;
This gave me a redefinition error, but I thought that delete[] frees the space in memory (and thus 'arr'). I know how to work around this (new array name, don't delete[]/redefine), but I was wondering what's actually going on that gives the error?
You might want to try this:
int size = 5;
int* arr = new int[ size ];
for( int i = 0; i < size; i++ )
arr[ i ] = i;
delete[] arr;
size = 10;
arr = new int[ size ]; //<-- no int* here, we just need to reassign
for( int i = size; i > 0; i-- )
arr[ i ] = i;
delete[] arr;
We are indeed deallocating the block of memory arr points to, but that doesn't mean we are removing the int* arr. We just removed it's 'content'.
It's just a non assigned pointer again after we delete it.
The arr
is declared twice. You can reuse it but without declare it again.
size = 10;
int* arr = new int[ size ];
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.