Dynamicly creating arrays of char *

Started by
4 comments, last by Bleakcabal 20 years, 1 month ago
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.
WHO DO THEYTHINK THEY'REFOOLING : YOU ?
Advertisement
I think you want to do this instead:

char **command;
command = (char **) malloc(numberOfParam * sizeof(char *));
Thanks it works now !
WHO DO THEYTHINK THEY'REFOOLING : YOU ?
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''.
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
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.
WHO DO THEYTHINK THEY'REFOOLING : YOU ?
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]
"THE INFORMATION CONTAINED IN THIS REPORT IS CLASSIFIED; DO NOT GO TO FOX NEWS TO READ OR OBTAIN A COPY." , the pentagon

This topic is closed to new replies.

Advertisement