dynamic memory allocation question

C

Chris

Can you make an array of classes with dynamically allocated members?
For example:
###
class LIST {
public:
char * data;
LIST() {
data = (char *) malloc(10*sizeof(char); }
~LIST() { free(data); } };
LIST lists[52];
###
Is this legal? Also, can I reallocate the memory that was allocated in
the example?
###
lists[14].data = (char *) realloc(lists[14].data, 16*sizeof(char));
###

Thanks for any help!
-Chris
 
C

Chris

Another question (sorry). Is it possible to dynamically allocate these
classes?
###
LIST * lists = (LIST *) malloc(sizeof(LIST));
###
 
V

Victor Bazarov

Chris said:
Can you make an array of classes with dynamically allocated members?

Yes, *I* can.
For example:
###
class LIST {
public:
char * data;
LIST() {
data = (char *) malloc(10*sizeof(char); }
~LIST() { free(data); } };

Missing the copy constructor and the copy assignment op. Read about
"the Rule of Three".
LIST lists[52];
###
Is this legal?
Yes.

Also, can I reallocate the memory that was allocated in
the example?
###
lists[14].data = (char *) realloc(lists[14].data, 16*sizeof(char));
###

I don't know. Can you? The main question, of course, should you?
And if you need to ask all those questions, you probably shouldn't.
Use 'std::vector<char>' or 'std::string' instead.

V
 
V

Victor Bazarov

Chris said:
Another question (sorry). Is it possible to dynamically allocate these
classes?
###
LIST * lists = (LIST *) malloc(sizeof(LIST));
###

Yes, it's possible, but not this way. You _have_ to use 'new'.

V
 
C

Chris

The main reason I ask these questions is because I'm trying to get
understanding, not necessarily the safest way to do it. I'm a very
amature programmer, and do it as a hobby. But thank you, I will look
into vectors.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,754
Messages
2,569,521
Members
44,995
Latest member
PinupduzSap

Latest Threads

Top