C - 如果最大长度大于 50,则返回变量始终为空

标签 c return-value fgets

我真的被这个难住了。

我用 c 语言编写了一个简单的程序来从用户键盘输入中检索名字、姓氏和 YOB(出生年份)(我还没有抽出时间将年龄解析为整数)并且我设置了最大值输入的字符数。

但每当我允许字段的最大字符数为 50 或更大时,返回值始终为空。

这是代码(60 行),后面是输出。导致问题的函数是倒数第二个函数,getInputNoNewLine:

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

void flushBuffer();
char *getInput(int max, char message[]);
char *getInputNoNewline(int max, char message[]);

typedef struct Person {
    char *firstName;
    char *lastName;
    int yob;
} Person;

void flushBuffer() {
    int ch; 
    while ((ch = getchar()) != '\n' && ch != EOF); //flush the input buffer
}

char *getInput(int max, char message[]) {
    char in[max];
    char *input;
    do {
        printf("%s", message);
        input = fgets(in, max + 2, stdin); //max + 2 accounts for characters fgets adds
        if (input[strlen(input)-1] != '\n') {
            printf("Sorry, maximum %d characters\n", (max));
            flushBuffer();
        }
    } while (input[(strlen(input)-1)] != '\n');
    printf("input: %s", input); //debug
    return input;
}

//OFFENDING FUNCTION
char *getInputNoNewline(int max, char message[]) {
    char *input;
    input = getInput(max, message);
    printf("raw input : %s", input); //debug
    if (input[strlen(input) - 1] == '\n') { //strip new line character
        input[strlen(input) - 1] = '\0';
    }
    printf("final input: '%s'\n", input); //debug
    return input;
}

int main(int argc, char *argv[]) {
    int numPlayers = 3;
    char *intIn;
    int i = 0;
    Person players[numPlayers]; 
    printf("Hello world Game\n");
    for (i = 0; i < numPlayers; ++i) {
        players[i].firstName = getInputNoNewline(50, "What is your first name: "); //50 will return blank
        players[i].lastName = getInputNoNewline(49, "What is your last name: "); //49 will return fine
        intIn = getInputNoNewline(4, "What is your YOB: "); //TODO: convert number to integer with sscanf
        printf("-----------------------------------\n");
    }
    printf("Finished\n");
    return 0;
}

这是输出,如您所见,jim 的第一个输入是从 fgets 接收的,但返回值为空(原始输入 : )。如果我要将最大值从 50 减少到 49,按照姓氏字段的情况,它工作得很好。有什么想法吗?

Hello world Game
What is your first name: jim
input: jim
raw input : final input: ''
What is your last name: smith
input: smith
raw input : smith
final input: 'smith'
What is your YOB: 1984
input: 1984
raw input : 1984
final input: '1984'
-----------------------------------

最佳答案

您的代码有一个未定义的行为
您正在返回一个指向本地分配数组的指针。

char *getInput(int max, char message[])
{
    char in[max];
    ....
    ....
    return input;
}

in 是函数局部数组,保证仅在函数作用域 {``} 之前有效。为了能够超出函数范围访问此数组的内容,您需要通过以下方式增加数组的生命周期:

  • 使用 malloc
  • 动态分配它
  • 使其成为静态或全局

如果您使用 malloc,请不要忘记在使用后通过调用 free 释放数组,否则会导致内存泄漏。

关于C - 如果最大长度大于 50,则返回变量始终为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14805732/

相关文章:

javascript - 使用外部内联脚本作为本地函数

java - 是否有返回 true、false 或 unknown 的 Java 约定?

c - 自动使用fgets()测试程序

c - Strncmp:异常段错误

c - 逆环索引以获得最大索引作为 C 上第一个索引的第一个

c - 使用 PIC 微处理器上的 C 语言进行二进制输出以实现 MIDI 输出

vb6 - 如何从函数返回值

c - 如何删除数组中的特定单词?

c - 将图像划分为不规则区域

c - 如何创建一个简单的驱动程序? [乌类图]