Jazz Jazz - 12 days ago 7
C Question

C: Printing the longest word in a string and its length

I'm beginning with C language and I'm learning it through a platform that checks automatically the code I write (e.g., it gives me some task and after uploading the code it checks whether what I wrote gives meaningful results).

So far all has been working fine, but I'm stuck with one problem that, to my eye I've solved, but after uploading the code and running it, an error occurs that I frankly don't understand.

TASK: Print the longest word in a sentence, and its length.

My Attempt:

#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;

}


For instance if one writes

hello my name is jacksparrowjunior goodbye


one gets

jacksparrowjunior 17


And the error is this:

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==


The other thing I noticed, is that if I change

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


to

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


I get an error after running the program in my computer.

Answer

Depending on the given Data and without testing I would guess you should initialize str and word to ""

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