2016-03-28 145 views
4

编辑:我删除了内存分配声明并将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 
+0

'nextToken()'定义在哪里? –

+1

'nextWord','nextToken'?这是什么? –

+0

对不起,我的意思是nextWord。我编辑了代码。 – Shx

回答

2

strlen()只给你的字符数,除空字符。您还需要为空字符分配内存。

+1

我向malloc(sizeof(char)* strlen(bufferPointer))添加了一个+1,它起作用!非常感谢! – Shx

+0

@Shx:请帮助你自己,不要在多个连续的行上使用'strlen(bufferPointer)'。使用:int L = strlen(bufferPointer);'然后用'L'代替。您的代码将获得可读性提升。 'sizeof(char)= 1'是为永恒定义的,我猜想。 – ikrabbe

+0

@ikrabbe C99,第6.5.3节。4:“当应用于具有char类型,unsigned char或signed char(或其限定版本)的操作数时,结果为1.” – Kupiakos

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任何地方都没有。

+0

我正在返回令牌,因为我想返回已删除的单个单词。 bufferpointer将返回整个字符串减去删除的单词。如果我误解了你的评论,请告诉我。此外,如果您可以指出内存泄漏可能发生的一般区域,我会非常感激,所以我可以看看并尝试调试。 – Shx