Dynamically allocating an array of pointers

B

bintom

We can dynamically allocate memory using the 'new' operator.

char *cptr = new char[21];

Now, I'm trying to dynamically allocate 3 strings with the following
code on Dev C++. However, an error message 'Invalid initializer' is
generated. Can anyone tell me how to do it correctly?

char *cptr[3] = new char[3][21];

Thanks,
Bintom
 
S

Sjouke Burry

bintom said:
We can dynamically allocate memory using the 'new' operator.

char *cptr = new char[21];

Now, I'm trying to dynamically allocate 3 strings with the following
code on Dev C++. However, an error message 'Invalid initializer' is
generated. Can anyone tell me how to do it correctly?

char *cptr[3] = new char[3][21];

Thanks,
Bintom
Make the array def equal on both sides?
Like optr is a pointer to a char array[3][21]?
 
M

Miles Bader

bintom said:
Now, I'm trying to dynamically allocate 3 strings with the following
code on Dev C++. However, an error message 'Invalid initializer' is
generated. Can anyone tell me how to do it correctly?

char *cptr[3] = new char[3][21];

char *cptr[3];
for (unsigned i = 0; i < 3; i++)
cptr = new char[21];

-miles
 
M

Miles Bader

Miles Bader said:
Now, I'm trying to dynamically allocate 3 strings with the following
code on Dev C++. However, an error message 'Invalid initializer' is
generated. Can anyone tell me how to do it correctly?

char *cptr[3] = new char[3][21];

char *cptr[3];
for (unsigned i = 0; i < 3; i++)
cptr = new char[21];


Hmm, I guess you really want this maybe:

char (*cptr)[21] = new char[3][21];

-miles
 
$

$|\\/@

Hey Miles,Your apology makes a lot of sense to me. Thanks,

Bintom

in my college lab exercise we did the following for int data type.
Hope it works incase of char.

char **temp;
*temp = (char *)malloc(3*21);
 
I

Ian Collins

in my college lab exercise we did the following for int data type.
Hope it works incase of char.

char **temp;
*temp = (char *)malloc(3*21);

That's bad on two counts:

1) You dereference temp before assigning to it.
2) You pass a magic number 3*21 without explanation.

and you cast the return on malloc!
 
I

Ian Collins

That's bad on two counts:

1) You dereference temp before assigning to it.
2) You pass a magic number 3*21 without explanation.

and you cast the return on malloc!

Oops, as the code looked like C, I assumed it was!
 

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

Forum statistics

Threads
473,755
Messages
2,569,534
Members
45,008
Latest member
Rahul737

Latest Threads

Top