Im trying to make a function that will split the words (like perl's split and php's explode), but im getting a couple of errors which I don't understand.
Errors:
Code:
$ gcc -W -Wall ptr_explode.c -o ptr_explode
ptr_explode.c: In function `ptr_explode':
ptr_explode.c:25: warning: `return' with a value, in function returning void
ptr_explode.c: In function `main':
ptr_explode.c:33: error: void value not ignored as it ought to be
ptr_explode.c:36: warning: passing arg 1 of `puts' makes pointer from integer without a cast
Code:
Code:
#include <stdio.h>
#include <string.h>
void ptr_explode(char *ptr)
{
//char *ptr = "a pointer with a buch of words un fun funf unf ";
/* first 'convert' the pointer into a string so that we can use strtok */
int ptrlen = strlen(ptr);
char string[ptrlen];
strcpy(string, ptr);
char *result = NULL;
int ntokens = 0;
char words[128][256];
result = strtok(string, " ");
while (result != NULL) {
strcpy(words[ntokens++], result);
result = strtok(NULL, " ");
}
// puts(words[1]);
return words;
}
int main(void)
{
char *ptr = "a pointer with a buch of words un fun funf un";
char *exploded;
exploded = ptr_explode(ptr);
// supposed to print the 2nd word ("pointer")
puts(exploded[1]);
return 1;
}
And here's the original code that works (and compiles without a single error) which im trying to make into a function:
Code:
#include <stdio.h>
#include <string.h>
int main(void)
{
char *ptr = "a pointer with a buch of words un fun funf unf ";
int wtf = strlen(ptr);
char string[wtf];
strcpy(string, ptr);
char *result = NULL;
int ntokens = 0;
char words[256][256];
result = strtok(string, " ");
while (result != NULL) {
strcpy(words[ntokens++], result);
result = strtok(NULL, " ");
}
// prits the second and third word ("pointer", "width")
puts(words[1]);
puts(words[2]);
return 0;
}