簡體   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