简体   繁体   中英

I still don't understand C++ operator new[] (or new[][])

I've typically shied away from unnecessary C++ features but as time marches on I can't avoid confronting my gremlins. Most recent of all is operator new[] and the potential for memory problems.

char *playerNewNames = new char[numPlayers][50];

It's great to know we don't need so many pointer * indirections and I'd feel confident in C iterating with malloc but the above seems a step too far. My compiler didn't complain but I want to be sure I will be getting an array of size numPlayers with each indexing a tranche of 50 characters. And how would I deallocate this?

I will try delete[][] but even if that doesn't throw it isn't 100% obvious that it will clean up everything, without iteration on my part. Please can somebody explain. Thanks in advance.

char *playerNewNames = new char[numPlayers][50]; is a mistake. You should get a compiler error. The correct syntax is:

char (*playerNewNames)[50] = new char[numPlayers][50];

and to delete it:

delete[] playerNewNames;

However a much better option would be to not use C-style arrays, and not use new . Instead, use container classes which manage the memory for you, such as std::vector or std::array .

The only proper way to deallocate an array is to use delete[]

delete deallocated single object while delete[] dealocates an array of objects. there is no such thing as delete[][] or delete[][][]

It looks like you want an array of arrays.

The most readable way, in my opinion, is to use a type alias.

typedef char PlayerName[50];

PlayerName* playerNewNames = new PlayerName[numPlayers];

delete [] playerNewNames;

If you want an array of pointers to arrays, you're going to need to iterate, but since you want all the "inner" arrays to have the same size, and it is known at compile time, that seems like a bad idea.

And learn about std::vector and std::array .

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM