【问题标题】:How could calling another function fill in the elements of the array in C?调用另一个函数如何填充 C 中数组的元素?
【发布时间】:2019-05-27 02:49:57
【问题描述】:

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

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 "\304\365\377~\300\365\377~", 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 "\304\365\377~\300\365\377~", lim=100)
at test.c:15
15      s[i]=c;
(gdb) p s
$1 = 0x7efff574 "\304\365\377~\300\365\377~"
(gdb) p i
$2 = 0
(gdb) p c
$3 = 72
(gdb)    

问题:

  1. 如果执行所有这些操作的函数(即“函数”)只能返回整数,那么如何用值填充数组“array1”的元素?

  2. 为什么输出字符串要加上“vL±~ó°~£Cnr

  3. 这个符号是什么意思:"0x7efff574 "\304\365\377~\300\365\377~",如果你能在文档中指出我的某个地方吗?

【问题讨论】:

    标签: c bash gdb centos7 cc


    【解决方案1】:
    1. 函数不能返回数组 - 它只能返回标量、结构或联合,或者根本没有值。

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

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

      s[i] = 0;
      

      就在return i;之前

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


    附:请正确且一致地缩进您的代码。省掉空格键,破坏代码

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-10
      • 1970-01-01
      • 2023-03-07
      相关资源
      最近更新 更多