简体   繁体   中英

Longest in string

#include <stdio.h>
#include <string.h>
int main()
{
    char string[100], word[20], max[20];
    int i = 0, j = 0, flag = 0;
    printf("Enter string: ");
    gets(string);
    for (i = 0; i < strlen(string); i++)
    {
        while (i < strlen(string) && string[i]!=32 && string[i]!=0)  //line 1
        {
            word[j++] = string[i++];
        }
        if (j != 0)
        {
            word[j] = '\0';
            if (!flag)
            {
                flag = !flag;
                strcpy(max, word);
            }
            if (strlen(word) > strlen(max))
            {
                strcpy(max, word);
            }
            j = 0;
        }
    }
    printf("The largest word is '%s' .\n", max);
    return 0;
}

I came across this code that finds the longest word in a given string and returns the last one in case of multiple occurrences of same length word

(1) I do not understand why output does not depend upon max[], I mean finally we are printing the longest word out of max[] and its size is max[20] but even for very large words it gives correct output, changing this to max[10] also works.

(2) In line 1 why we are testing string[i]!=0 since removing this has no effect and we have already tested i < strlen(string) in first part of while loop. But when i try string[i]!='\\0' i get incorrect output for some input strings.

Where am i missing the logic for these two?

@callyalater, I put max[] before word[] and string[] but it has no effect on output but for max[5] and input string "arrenhius equation is hard to decipher zxcvbnmlkjhgfdsaqwertyuiop" the output is 'arrenzxcvbnmlkjhgfdsaqwertyuiop' on the online compiler link provided but works fine for max[10] but in my compiler(dev c++) the output gives correct results for max[5] and max[10] both which is 'zxcvbnmasdfghjklqwertyuiop'.

char string[100], word[20], max[20];
int i = 0, j = 0, flag = 0;

Over-running max, will modify i or word

The memory could be used as below

+-------+-------------+-------+
| word  | max         | i     |
+-------+-------------+-------+

or

+-------+-------------+-------+
| i     | max         | word  |
+-------+-------------+-------+

So writing more than 20 bytes into max, could modify word, or i - as it overruns.

When you overrun these memory items, you enter undefined behavior, which may work (as you found) or crash.

The string[i] !=0 is protecting against some of these failings.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM