gpt4 book ai didi

来自 K&R 的 C 函数和变量作用域

转载 作者:太空宇宙 更新时间:2023-11-04 08:44:32 25 4
gpt4 key购买 nike

我目前正在阅读 K&R,这段代码让我感到困惑,尤其是涉及到变量/函数范围时...

#include <stdio.h>
#define MAXLINE 1000

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

/*print the longest input line*/
void 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;
}

/*getline: read a line into s, return length*/
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;
}

/*copy: copy 'from' into 'to': assume to is big enough*/
void copy(char to[], char from[])
{
int i;

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

}

getline() 函数如何将范围保存到位于 main() 中的 line[] 数组中?

copy() 函数如何将范围保存到位于 main() 中的 longest[] 数组中?

如果函数嵌套在 main() 中,我能理解,但在这个例子中它们不是。

最佳答案

基本上,您将指向数组第一个元素(在 main 中声明)的指针传递给您的函数。为了更清楚,原型(prototype)也可以写成

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

当您从 main 调用您的函数并将数组名称作为其参数传递时,数组名称将转换为指向其第一个元素的指针。所以,复制到函数参数中的是数组的起始地址,而不是数组本身。现在对传递的地址(即数组)的任何更改也会反射(reflect)到 main

关于来自 K&R 的 C 函数和变量作用域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22197468/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com