已编辑:我删除了内存分配声明,并将strlen(bufferPointer)更改为strlen(inputLine)。这似乎摆脱了我的输出中的奇怪符号。
我试图编写一个方法来删除字符串中的第一个单词,并返回删除单词的char指针。因为删除了这个单词,所以应该减少字符串的大小。
我遇到了一个奇怪的输出,我不知道为什么。
我对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
答案 0 :(得分:2)
strlen()
仅为您提供字符数,不包括空字符。您还需要为空字符分配内存。
答案 1 :(得分:0)
您正在返回令牌。相反,你应该返回bufferPointer。
return bufferPointer.
还有一点,代码中有几处内存泄漏。
根据您的要求,以下是要点。
上述程序中的内存泄漏如下所示。
//Allocate memory to newArray
char *newArray = malloc(sizeof(char)*strlen(bufferPointer));
// A memory address is given to newArray here which is
// over-written in following statement. So the above allocated
// memeory is a leak.
newArray = backup;
//allocate memory to token (returned variable)
char *token = malloc(sizeof(char)*strlen(bufferPointer));
token = strtok(newArray, " ");
//There is no need to allocate memory to hold an address of a string.
// only a character pointer is enough. So, the above allocated memory
// is again a leak.
并且定义了两个额外的变量,这些变量不是必需的。
1)变量 bufferPointer 可以替换为 inputLine ,因为字符数组的名称也是C中的指针。
2)你根本没有在任何地方使用 numOfWords 。