我從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);
我在我的電腦上運行該程序後得到一個錯誤。
的'word'最初是不確定的內容,因爲你不初始化這個緩衝區。因此,在未初始化的緩衝區上執行「strlen」會導致未定義的行爲。 –