Problem in Example 1.9 - The C Programming Language

I have tried to compile and run the program below which is the example 1.9 of the book The C Programming Language. It is compiled OK and no errors are found. However, when I run it and see if the program works, instead of returning me the longest line, it returns a sequence of garbage characters with the same length of the longest line.

Here is the program:

#include <stdio.h>
#define MAXLINE 1000

int getline(char line[], int maxline);
void copy(char to[], char from[]);

int main()
{
    int len;
    int max;
    char line[MAXLINE];
    char longest[MAXLINE];

    max = 0;
    while ((len = getline(line, MAXLINE)) > 0) {
        if (len > max) {
            max = len;
            copy(longest, line);
        }
    }

    if (max > 0) {
        printf("%s", longest);
    }
    return 0;
}

int getline(char s[], int lim)
{
    int c, i;

    for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i) {
        s[i] = c;
    }
    if (c == '\n') {
        s[i] = c;
        ++i;
    }
    s[i] = '\0';
    return i;
}

void copy(char to[], char from[])
{
    int i;

    i = 0;
    while ((to[i] = from[i] != '\0')) {
        ++i;
    }
}

Upvotes: 0

Views: 315

Answers (1)

Acorn
Acorn

Reputation: 26076

This expression:

(to[i] = from[i] != '\0')

is not doing what you think. It will compare from[i] != '\0' first, and assign the result to to[i]. This means the destination string will be the correct length but full of characters with code 1.

So probably you copied the parenthesis in the wrong position:

(to[i] = from[i]) != '\0'

Upvotes: 3

Related Questions