What I want my program to do is to read an input text from the user, tokenize that string with the whitespace being the delimiter and store each of the tokens int an array of char* which will then be returned.
here is a snippet of code that I am trying to make it work correctly:
typedef char* String;
String* split(char* cmd)
{
char* param;
char tmp[128];
String* result = (String*) malloc(10*sizeof(String));
memset(result,NULL,10);
strcpy(tmp,cmd);
param = strtok(tmp," ");
int index = 0;
while(param && index < sizeof(result) / sizeof(*result))
{
result[index] = (char*) malloc(strlen(param));
strcpy(result[index],param);
param = strtok(NULL," ");
index++;
}
}
Where cmd is the string that I am tokenizing and result is the array that will contain each token.
This snippet causes errors when trying to iterate through the returned result using a simple for loop (A segmentation fault arises)
String* splittedCmd = split(command);
int i;
for(i=0;i<10;i++)
{
if(splittedCmd[i] != NULL)
printf("%s\n",splittedCmd[i]);
}
strncpy
instead. Think about marking this as "homework". And think about switching to C++. – Kerrek SB