Skip to main content
gamedev.net
🔒 Locked

Quick dynamic memory question (c++)

Started by fiwl 1 reply 450+ views
Original Post
fiwl
fiwl
hi, as the board is in a dynamic memory mood at the moment, i have a quick question. i have been told that you cant use ''new'' to create a memory block of referance types because they are not objects. (e.g. a list of pointers) [source msdn docs]. is this true? if so, should i revert back to malloc and calloc instead? (btw, using new in this way DOES seem to cause errors that calloc does not. am i using it right? if it is possible, what would be correct syntax for an array of character pointers for example)? thanks, fiwl.
Kylotan
Kylotan
No, when it says 'reference types' it means 'references'. You can't do this because references need to be initialised at the point of creation. You certainly can create an array of pointers legally.

Regarding new/calloc, new calls the default constructor for the elements (which in the case of default types, usually means nothing), while calloc calls no constructor but initialises to zero. In C++ programs you rarely need malloc or calloc.

[ MSVC Fixes | STL Docs | SDL | Game AI | Sockets | C++ Faq Lite | Boost
Asking Questions | Organising code files | My stuff | Tiny XML | STLPort]


[edited by - Kylotan on March 19, 2003 1:28:11 PM]
JohnBolton
JohnBolton
quote:
Original post by fiwl
(btw, using new in this way DOES seem to cause errors that calloc does not. am i using it right? if it is possible, what would be correct syntax for an array of character pointers for example)?



Your errors might be caused by not initializing the newly allocated array of pointers.

char * * array = new char * [ array_size ];
memset( array, 0, array_size * sizeof( char *) );

is essentially the same as

char * * array = (char * *)calloc( array_size * sizeof( char * ) );
John BoltonLocomotive Games (THQ)Current Project: Destroy All Humans (Wii). IN STORES NOW!

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.