2016-11-27 137 views
2

我从C语言开始,通过一个自动检查我写的代码的平台来学习它(例如,它给了我一些任务,并且在上传代码检查我写的是否给出了有意义的结果)。C:打印字符串中最长的单词及其长度

到目前为止,所有的工作都很好,但我坚持一个问题,在我看来我已经解决了,但是在上传代码并运行后,发生了一个我坦率地不理解的错误。

任务:打印句子中最长的单词及其长度。

我尝试:

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 

int main() 
{ 
    char str[80], word[80]; 
    fgets(str, 80, stdin); 

    char *token; 

    //tokenizing array str 
    token = strtok(str, " "); 


    while(token != NULL) 
    { 
     if(strlen(word) < strlen(token)) 
     { 
      strcpy(word, token); 
     } 

     token = strtok(NULL, " "); 

    } 

    printf("%s %d", word, strlen(word)); 




    return 0; 

} 

举例来说,如果一个写

hello my name is jacksparrowjunior goodbye 

一个得到

jacksparrowjunior 17 

和错误是这样的:

TEST 
PASSED 
==20760== Conditional jump or move depends on uninitialised value(s) 
==20760== at 0x4006B9: main (004799.c:18) 
==20760== Uninitialised value was created by a stack allocation 
==20760== at 0x400660: main (004799.c:6) 
==20760== 
==20760== Conditional jump or move depends on uninitialised value(s) 
==20760== at 0x4006E5: main (004799.c:18) 
==20760== Uninitialised value was created by a stack allocation 
==20760== at 0x400660: main (004799.c:6) 
==20760== 

我注意到的另一件事是,如果我改变

char str[80], word[80]; 
     fgets(str, 80, stdin); 

char str[1000], word[1000]; 
     fgets(str,1000, stdin); 

我在我的电脑上运行该程序后得到一个错误。

+3

的'word'最初是不确定的内容,因为你不初始化这个缓冲区。因此,在未初始化的缓冲区上执行“strlen”会导致未定义的行为。 –

回答

2

根据给定的数据,并没有测试我猜你应该初始化STR和字为“”

[...] 
char str[80] = ""; 
char word[80] = ""; 
fgets(str, 80, stdin); 
[...] 
0

错误消息既有益的,神秘的。注意对有条件和未初始化的引用。所以你应该去看代码中的条件(“如果测试”)。

在错误的下一行提供线索在哪里看:线18项6