PDA

View Full Version : allocating mem for an array



Strut
10-19-2002, 04:33 AM
I'm curious as to how I would allocate memory as needed for a multideminsional array? ex:



char command_names [20]; //improper, yes I know

command_names=malloc(blah blah); //i got no clue



Any help? Do you understand what I'm doing? Its a character string, and I need to be able to store as much as that is needed.

Thanks.

shaik786
10-19-2002, 04:50 AM
>char command_names [20]; //improper, yes I know
Is totally wrong in the declaration itself. If you want to declare 20 pointers to type 'char *', then this is the way you do it:

char *command_name[20];

Now that you declared 20 pointers, they are randomly pointing to some memory location in you physical RAM. You need to make them point to your program's address space, so you use malloc() to allocate memory in your address space, and make these pointers point to the returned allocated space by. To allocate, you do:

command_name[0] = malloc(100); /* 100 bytes are retrned */
command_name[1] = malloc(100);
.
.
.

Strut
10-19-2002, 05:03 AM
shaik, yes I know the decleration was all wrong. I wrote it like that to show that the wasn't known. As in I need to allocate the to how ever character strings I may need.


I appreciate both your replies. Thank you for your help. I'll see what I can.