gpt4 book ai didi

c - While 循环按引用传递字符数组

转载 作者:太空宇宙 更新时间:2023-11-04 02:06:21 24 4
gpt4 key购买 nike

因此,我正在尝试确定最长的学校作业队列。这是我认为有问题的代码。我不明白为什么“longest_line”在 while 循环中打印良好,但不会在循环外打印。

    int main() {
int ch;
char line[MAXLINE] = { '\n' }; /* current input line */
char longest_line[MAXLINE] = { '\n' }; /* copy of longest line */

while ((ch = readline(line, MAXLINE)) != EOF) {
if (longest(line, longest_line))
copy(longest_line, line);
printf("Read Line: %s\n", line);
printf("Long Line: %s\n", longest_line);
}

printf("Print Long Line: %s\n", longest_line);

这是输出:

calc L
copy
Read Line: sdafasdfsadfsadfs
Long Line: sdafasdfsadfsadfs
calc L
Read Line: sadfs
Long Line: sdafasdfsadfsadfs
calc L
Read Line: sdfasdfsafd
Long Line: sdafasdfsadfsadfs
calc L
Read Line: sadfsdf
Long Line: sdafasdfsadfsadfs
calc L
Read Line: sadfs
Long Line: sdafasdfsadfsadfs
calc L
Read Line:
Long Line: sdafasdfsadfsadfs
calc L
Read Line: sfsafsdfsf
Long Line: sdafasdfsadfsadfs
Print Long Line:

这就像 longest_line 在循环后被删除,这对我来说没有意义。对不起,我是新手。感谢知道此异常背后的技术原因的人。

如果你想运行它,这是我的整个程序:(我修复了变量)

#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>

#define MAXLINE 80 /* maximum input line size */

/* function declarations */
int readline( char line[], int max );
void copy( char to[], char from[] );
bool longest( char read_line[], char previous_line[] );

/* print longest input line */

int main() {
int ch;
char line[MAXLINE] = { '\n' }; /* current input line */
char longest_line[MAXLINE] = { '\n' }; /* copy of longest line */

while ((ch = readline(line, MAXLINE)) != EOF) {
if (longest(line, longest_line))
copy(longest_line, line);
printf("Read Line: %s\n", line);
printf("Long Line: %s\n", longest_line);
}

printf("Print Long Line: %s\n", longest_line);

return 0;
}

/* readline: read a line into s, return length */
int readline(char s[], int lim) {
int i = 0; // the current index
char c; // the current char

c = getchar();
while (c != '\n' && i < lim) {
s[i] = c;
i++;
c = getchar();
}
s[i] = '\0'; // final charachter of string

return c;
}

/* copy: copy 'from' into 'to'; assume to is big enough */
void copy(char to[], char from[]) {
int i;
for (i = 0; to[i] = from[i]; ++i);
printf("copy\n");
}

/* longest: Which line is the longest */
bool longest( char read_line[], char previous_line[] ) {
printf("calc L\n");
char ch;
int size_read = 0;
int size_previous = 0;

// determine length of read line
ch = read_line[size_read];
while (ch != '\0') {
ch = read_line[size_read];
++size_read;
}

// determine length of previous line
ch = previous_line[size_previous];
while (ch != '\0') {
ch = previous_line[size_previous];
++size_previous;
}

// determine longest line
if (size_read > size_previous)
return true;
else
return false;
}

最佳答案

我不会透露细节,但代码中有几个地方无法初始化变量,导致 undefined behaviour .

关于c - While 循环按引用传递字符数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20253550/

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