通过参考传递循环字符数组

时间:2013-11-27 21:36:49

标签: c arrays loops

所以我正在努力确定学校作业的最长线。这是我认为有问题的代码。我不明白为什么“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;
}

1 个答案:

答案 0 :(得分:3)

我不会提供详细信息,但代码中有几个地方无法初始化变量,导致undefined behaviour