简体   繁体   中英

The longest string

I'm going through K&R C programming language book and try to solve all the exercises.

There is a sample program that finds the longest string in the input. It basically reads strings from input one by one and store the longest in the array with pre-defined length. In other words it assumes the upper bound on the length of the longest string.

After this program there is an exercise that asks to change the program such that it does not assume the bound on the length. I have no idea how to achieve this without using dynamic memory allocation (which is discussed in the following chapters of the book).

If I'm correct, arrays in C are defined during the compilation so their length is static unless we allocate memory dynamically.

I'm assuming you are referring to exercise 1.16 on page 30. The complete statement is

Exercise 1-16. Revise the main routine of the longest-line program so it will correctly print the length of arbitrarily long input lines, and as much as possible of the text.

It is impossible to return the whole string if its length is arbitrary, because you would have to store it, and that would require dynamic memory allocation. However, you can slightly modify the main routine so it will correctly compute the length of the string, and output "as much as possible" of the text, ie up to a fixed length.

Here is one possible answer:

#define MAXLINE 1000 /* maximum input line size */

main() {
    int buf_len; /* current buffer length (<= MAXLINE) */
    int len = 0; /* current full line length */
    int max = 0; /* maximum length seen so far */
    char buffer[MAXLINE];  /* current input line */
    char line[MAXLINE];    /* prefix of longest-line candidate */
    char longest[MAXLINE]; /* longest line saved here */

    while ((buf_len = getline(buffer, MAXLINE)) > 0) {
        if (len == 0) /* this is the first chunk of the string */
            copy(line, buffer);
        len += buf_len;
        if (buf_len < MAXLINE || buffer[MAXLINE-2] == '\n') {
            /* the string was terminated */
            if (len > max) {
                max = len;
                copy(longest, line);
            }
            /* this line was fully processed */
            /* now reset len to 0 and process the next string */
            len = 0;
        }
    }
    if (max > 0)
        printf("%s", longest);
    return 0;
}

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