【问题标题】:What is wrong with my function and main method?我的功能和主要方法有什么问题?
【发布时间】:2014-04-23 11:06:12
【问题描述】:

我正在编写一个具有 2 个函数和一个主函数的 C 程序。第一个函数读取并存储字符(更多描述包含在下面的评论中)。我不确定我是否正确终止了字符串(使用 0)??
提前感谢您的帮助!

#include <stdio.h>
#define MAX 20


/* reads a line from the keyboard and stores the characters in the array str.
If the user enters more than max characters, it returns -1. Function should terminate             
the char array with a NULL (or 0) */

int getline(char str[], int max){
    char c, i;

    while((c = getchar()) != '\n'){
        str[i] = c;
        i = i + 1;
    }

    str[i] = '\0';

    if (i < MAX)
        return 0;
    else
        return -1;
}

/* calculates and returns  the length of the array passed to it */
int strlen(char str[]){
    int i = 0;

    while(str[i] != NULL)
        i++;

    return i;
}


main(){
    char str[MAX];
    printf("Please Enter a String less than 20 characters:\n");

    if((getline(str, MAX)) == 0)
        printf("Length of ‘%s’ = %d", str, (strlen(str)));
    else
        printf("You Entered more than 20 Characters!");
}

【问题讨论】:

  • str[i] != NULL 可能会起作用,但它是不正确的。 NULL 是一个空 pointer 常量。你想要str[i] != '\0'

标签: c function return printf getline


【解决方案1】:

您必须在您的getline() 中将i 初始化为0。

另一方面,getline() 的第二个参数是max。但是您只在函数中引用了MAX。幸运的是,由于唯一调用getline() 的地方使用MAX 作为第二个参数,因此您不会观察到任何差异。此外,为了避免写出数组边界,您应该检查循环inside而不是循环之后的数组索引。

【讨论】:

  • 你能详细说明你对 MAX 的意思吗?那么它不会在循环内反复检查它吗?
  • 可以,但您应该反复检查。否则,当你在循环之后找到i &gt;= MAX 时,你已经写过了数组边界。
  • 这就是我输入超过 20 个字符时程序崩溃的原因吗?
  • & 是 C 中变量的默认值,不会自动为 0?
  • 是的。这就是为什么当您输入超过 20 个字符时程序崩溃而不是优雅地发出错误消息的原因;静态变量和全局变量自动初始化为0,但局部变量没有隐式初始化。
【解决方案2】:

getline(char str[], int max)

你还没有初始化局部变量i

【讨论】:

  • 所以在 C 中变量的默认值不会自动为 0?
  • 只有全局和静态初始化为0。局部变量包含垃圾值并需要初始化。
猜你喜欢
  • 1970-01-01
  • 2012-05-27
  • 1970-01-01
  • 2018-02-19
  • 2015-05-27
  • 2018-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多