I'm a beginner in C and I have this piece of code here, where I'm trying to tokenize a "string" input. I assume the answer is pretty obvious, but I am asking for help since I have reviewed the manual many times and simply can't find the bug. The purpose of tokenizing is to create separate process to execute basic linux commands since I'm trying to build a shell. Thank you all in advance.
//PROMPT is defined as "$"
void tokenizeInput(char input[]) {
char *piece;
int i = 0;
int *argument;
int pst[] = 0;
char temp = ' ';
piece = &temp;
piece = strtok(input, PROMPT);
while (input != NULL) {
(*argument)[pst] = piece;
strcat((*argument)[pst++], "\0");
piece = strtok(NULL, PROMPT);
puts(piece);
piece = NULL;
}
}
The error I get is expression must be a modifiable lvalue
, at [pst++]
which is an argument in strcat
.
Judging by your questions's title, I believe you would like some hints on using strok
. There follows a commented example (see bellow)
Your code, however, has some other problems. Function strtok
modifies the argument, so you would better pass it a char*
rather than a char[]
. Also pst[]
an array, while pst
itself is a constant-pointer (to the first block of memory where your array is allocated). You can't increment pst
. I guess you need an inter index for it. Or, perhaps, depending on the logic you have in mind, you want to increment pst[0]
, instead.
Do not hesitate to ask more.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main (int argc, char **argv)
{
char buffer[1024], *p;
/* This is an example of a line we ant to parse. */
strcpy (buffer, "Hello Token World");
printf ("Buffer is: %s\n", buffer);
/* The function strtok process the string in 'buffer' and finds the first
ocurrency of any of the characters present in the string 'delimiters'
p = strtok (char *buffer, char *deliminters)
The function puts a string-end mark ('\0') where it found the delimiter
and returns a pointer to the bining of the buffer.
*/
/* Finds the first white space in buffer. */
p = strtok (buffer, " ");
/* Now, go on searching for the next delimiters.
p = strtok (NULL, char *delimiters)
The function "remembers" the place where it found the delimiter.
If the furst argument is NULL, the function starts searching
from this position instead of the start of buffer. Therefore
it will find the first delimiter starting from where it ended
the last time, and will return a pointer to the first
non-delimiter after this point (that it, the next token).
*/
while (p != NULL)
{
printf ("Token: %s\n", p);
p = strtok (NULL, " "); /* Find the next token. */
}
/* Notice that strtok destroys 'buffer' by adding '\0' to every
ocurrency of a delimiter.*/
printf ("Now buffer is: %s\n", buffer);
/* See 'man strtok' or the libc manual for furter information. */
return EXIT_SUCCESS;
}