繁体   English   中英

C:找到最长的线

[英]C: find the longest line

这是 Dennis Ritchie 和 Brian Kernighan 所著的 The C Programming Language 一书(第二版)中的示例程序。 我的问题是,如果我们传递值(变量行)而不是对 function 长度的引用,那么更改如何反映在主 function 中?

#include <stdio.h>
#define MAXLINE 1000

int length(char s[], int lim);
void copy(char to[], char from[]);

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

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

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

    return 0;
}

int length(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;
    }
}

这个定义:

int length(char s[], int lim)

可以改写为:

int length(char *s, int lim)

这可能更容易理解。 我们不是按值传递变量,而是传递指针,因此 function 可以访问数据并在必要时对其进行修改。

len = length(line, MAXLINE)

在 C 中,所有 arrays 都是通过指针传递的。 所以 function length接收指向第一个字符的指针哦数组line ,它修改了这个数组

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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