如何调用另一个函数来填充 C 中数组的元素?

How could calling another function fill in the elements of the array in C?

• 我很难理解读取一组文本行并打印最长的程序 • 根据 K&R C (1.9),片段:

int my_getline(char line[], int maxline); /* my_getline should return only integer (not string) */
void copy(char to[], char from[]);
int main()
{
    int len; /* current line length */
    int max; /* maximum length seen so far */
    char line[MAXLINE]; /* current input line */
    char longest[MAXLINE]; /* longest line saved here */

    max=0;
    while ((len=my_getline(line,MAXLINE))>0)
        if (len>max) {
            max=len;
            copy(longest,line);
        }
    if (max>0) /* there was a line */
        printf("%s",longest); /* how can array 'longest' got filed with values */
    return 0;
} 

• 因此,我创建了另一个程序来简化它。

这是我的源代码:

#include <stdio.h>
#define MAX 100
int function(char i[], int);

int main() {
    char array1[MAX];
    function(array1,MAX);
    /* Using printf to print the 1st argument of function, which is array */
    printf("\nThis is THE STRING: %s\n", array1);
}

int function(char s[],int lim) {
    int c,i;
    for (i=0;i<lim-1&&(c=getchar())!=EOF&&c!='\n';++i)
        s[i]=c;
    return i; /* Does it mean, that the 'function' returns only integer 'i'? */
}

编译程序执行时:

pi@host:~/new$ cc -g test.c
pi@host:~/new$ a.out
hello, world

This is THE STRING: hello, worldvL±~ó°~£Cnr<€v@ v@¶~\áv=
pi@host:~/new$

当我尝试使用 gdb 进行调试时:

(gdb) run
Starting program: /home/pi/new/a.out 
Breakpoint 1, function (s=0x7efff574 "457~057~", lim=100)
at test.c:14
14      for (i=0;i<lim-1&&(c=getchar())!=EOF&&c!='\n';++i)
(gdb) n
Hello, world

Breakpoint 3, function (s=0x7efff574 "457~057~", lim=100)
at test.c:15
15      s[i]=c;
(gdb) p s
 = 0x7efff574 "457~057~"
(gdb) p i
 = 0
(gdb) p c
 = 72
(gdb)    

问题:

  1. 如何用值填充数组 'array1' 的元素,如果发生所有这些的函数 'function' 是只能返回整数?

  2. 为什么输出的字符串要加"vL±~ó°~£Cnr<€v@ v@¶~\áv="?

  3. 这个符号是什么意思:“0x7efff574”457~057~”,如果你能在文档中指出我的某个地方?

  1. 函数不能 return 数组 - 它只能 return 标量或结构或联合,或者根本没有值。

    但是除了 return 值之外,它还有副作用。这里,作为副作用,它修改了第一个元素由 s 指向的数组的内容。

  2. function 没有正确地以 null 终止字符串,因此将它与 printf 一起使用会导致未定义的行为。作为修复,添加

    s[i] = 0;
    

    就在 return i;

  3. 之前
  4. 表示法是指针值 0x7efff574 的十六进制地址,后跟该地址处以空字符结尾的字符串的内容,使用 \ooo 八进制转义表示不可打印人物。在这种情况下,数组在进入函数时包含一些随机垃圾。


P.S。请正确且一致地缩进您的代码。保留 space 栏并破坏代码