编辑:我删除了内存分配声明并将strlen(bufferPointer)更改为strlen(inputLine)。这似乎摆脱了我的输出中的怪异符号。尝试返回字符指针时出现奇怪的输出
我想写一个方法来删除字符串中的第一个单词,并返回删除单词的字符指针。由于这个词被删除,字符串的大小应该减少。
我遇到了一个奇怪的输出,我不知道为什么。
我对C相当陌生,刚开始熟悉指针的想法,所以任何帮助将不胜感激!
//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;
}
旧输出是:
there,
my
?²p
??
?²p?
?²p?
新的输出是:
there,
my
name
is
bob
'nextToken()'定义在哪里? –
'nextWord','nextToken'?这是什么? –
对不起,我的意思是nextWord。我编辑了代码。 – Shx