Disclosure: I'm trying to solve a challenge with strict time and memory limits. I would normally use vectors and strings, but here I need the fastest and smallest solution (with vectors it actually ran above the time limit), so I turned to dynamic arrays of char*. The relevant parts of my code:
char** substrings(string s, int* n){
*n = 0;
...
////////////////////////////////
char** strings = new char*[*n];
////////////////////////////////
for (int i = 0; i < s.length(); i++){
for (int j = 1; j < s.length() - i + 1; j++){
...
strings[si] = tmp;
...
}
}
return strings;
}
int main(){
...
for (int ti = 0; ti < t; ti++){
cin >> s;
char** substr = substrings(s, &n);
...
for (int i = 0; i < n; i++){
delete substr[i];
}
}
return 0;
}
Everything runs just fine without deleting the array (of arrays), but that is unacceptable, so how do I go about this? I've tried a lot of variations that seemed logical but I get runtime errors.
It is similar to allocating, but in reverse order, and using delete[]
instead of new[]
:
for(int i = 0; i < LENGTH; i++)
delete[] strings[i]; // delete each pointer in char** strings
delete[] strings; // finally delete the array of pointers
I assumed here that LENGTH
is the length of the array of pointers to char*
. So it looks that you only perform the first round of de-allocation
for (int i = 0; i < n; i++){
delete substr[i]; // need delete[] substr[i] here
but with delete
instead of delete[]
, you need delete[] substr[i]
instead, as my guess is that substr[i]
is a char*
pointer pointing the first element of an array of char
s allocated by new[]
. You finally need the additional
delete[] substr;
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.