Edited: I deleted memory allocation declarations and changed strlen(bufferPointer) to strlen(inputLine). This seems to get rid of the weird symbols in my output.
I'm trying to write a method to remove the first word in a string, and return char pointer of the word removed. Because this word is removed, the size of the string should be reduced.
I'm encountering a strange output and I'm not sure why.
I'm fairly new to C and just beginning to familiarize myself with the idea of pointers, so any help would be appreciated!
//global variables
char inputLine[] = "Hello there, my name is bob";
char *bufferPointer = inputLine;
char *nextWord();
main (){
printf("%s\n", nextWord());
}
char *nextWord(){
//calling a method that returns the number of words bufferPointer holds
int numOfWords = nwords(bufferPointer);
char *tmp2;
//Allocate memory to newArray
char *newArray = malloc(sizeof(char)*strlen(bufferPointer));
//create backup array
char backup[strlen(bufferPointer)];
strncpy(backup, bufferPointer, strlen(bufferPointer));
backup[strlen(bufferPointer)] = '\0';
//assign newArray pointer to backup array
newArray = backup;
//allocate memory to token (returned variable)
char *token = malloc(sizeof(char)*strlen(bufferPointer));
token = strtok(newArray, " ");
char *tmp = strchr(bufferPointer, ' ');
//move pointer to next word
if (tmp != NULL){
tmp2 = tmp;
bufferPointer = tmp +1;
}
return token;
}
Old output is:
there,
my
?²p
??
?²p?
?²p?
New output is:
there,
my
name
is
bob
nextToken()defined?nextWord,nextToken?? Which is it?