#### Archived

This topic is now archived and is closed to further replies.

# Dynamicly creating arrays of char *

This topic is 5399 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hi, I am programming in C ( not C++ ) and I want to dynamicly allocate memory for an array of string pointers. I need to do this because I am using the execv unix system call which must take an array of char *. When I do the following code :
char *command[3];
command[0] = "ls";
command[1] = "-r";
command[2] = NULL;
execv(my_strcat("/bin/", command[0]), command);

Everything goes fine, but when my program runs it does not know which command the user will enter and how many parameters it will have. So I cannot specify that char *command will be char *command[3] because there could be 0, 5, 2, etc. parameters. I have tried
char *command;
command = (char *) malloc(numberOfParam * sizeof(char *));

To dynamicly create the command array to the appropriate number of param but when I later try to do something like : command[0] = "ls"; command[1] = "-r"; command[2] = NULL; It gives me this error : error: invalid conversion from const char*'' to char'' What is the proper way to dynamicly create an array of char * ? Thank you in advance for any help you can provide.

##### Share on other sites
I think you want to do this instead:

char **command;
command = (char **) malloc(numberOfParam * sizeof(char *));

##### Share on other sites
Thanks it works now !

##### Share on other sites
Personally, for this specific purpose, I''d only allocate one char* array, put the whole command line in it, take pointers to the beginning of each argument (put them in an array, which can be dynamically allocated), and ''terminate'' each argument by replacing the appropriate whitespace characters with ''\0''.

##### Share on other sites
Since I allocated it like :
char **command;
command = (char **) malloc(numberOfParam * sizeof(char *));

Should I free this memory in a special way ? Or do I simply need to do free(command); ?

This is what I am doing right now but I wonder if this is ok since it is a double pointer and an array of string.

##### Share on other sites
quote:
Original post by Bleakcabal
Since I allocated it like :
char **command;
command = (char **) malloc(numberOfParam * sizeof(char *));

Should I free this memory in a special way ? Or do I simply need to do free(command); ?

This is what I am doing right now but I wonder if this is ok since it is a double pointer and an array of string.

Well if an element of the command array is also malloc'ed you need to free it to (offcourse before you free the whole array).

[edited by - George2 on March 2, 2004 12:44:58 PM]

1. 1
2. 2
3. 3
4. 4
Rutin
12
5. 5

• 26
• 10
• 9
• 9
• 11
• ### Forum Statistics

• Total Topics
633694
• Total Posts
3013378
×