Reputation: 456
I am not the best with pointers, so maybe you can see what I'm doing wrong.
Let's say that I have an array that was initialized like this:
char *arrayOfCommands[]={"ls -l", "wc -l"};
My goal is to get an array called char *currentCommand out of this array that looks at a specific cell of arrayOfCommands and separates the command into pieces on spaces.
My final goal would be to have a new currentCommand array on each loop that each look like this:
First Loop:
currentCommand = [ls][-l]
First Loop:
currentCommand = [wc][-l]
Here is the code I have so far:
for (i = 0; i < 2; ++i) {
char str[] = arrayOfCommands[i];
char * currentCommand;
printf ("Splitting string \"%s\" into tokens:\n",str);
currentCommand = strtok (str, " ");
while (currentCommand != NULL){
printf ("%s\n",currentCommand);
currentCommand = strtok (NULL, " ");
}
.
.
.
//Use the currentCommand array (and be done with it)
//Return to top
}
Any help would be greatly appreciated! :)
UPDATE:
for (i = 0; i < commands; ++i) {
char str[2];
strncpy(str, arrayOfCommands[i], 2);
char *currentCommand[10];
printf ("Splitting string \"%s\" into tokens:\n",str);
currentCommand = strtok (str, DELIM);
while (currentCommand != NULL){
printf ("%s\n",currentCommand);
currentCommand = strtok (NULL, DELIM);
}
}
I am getting this error: ** incompatible types in assignment**
It's talking about the "str" I'm passing the strtok function.
Upvotes: 0
Views: 381
Reputation: 59617
strtok
operates by modifying the string that you pass; this is easy to miss when using some man pages. Each command in your array is a literal string: attempts to modify them will cause problems. So you'll need to make a copy of each command before using it with strtok
.
Furthermore, this is an invalid initialization for an array:
char str[] = arrayOfCommands[i];
Declare str
as an array of some fixed size, then use strncpy
to make copies of each command before tokenizing them using strtok
:
char str[MAX_COMMAND_LEN + 1];
strncpy(str, arrayOfCommands[i], MAX_COMMAND_LEN);
// ...
Upvotes: 2