【问题标题】:passing uninitialized character array to function. Crashing将未初始化的字符数组传递给函数。崩溃
【发布时间】:2013-07-01 18:20:16
【问题描述】:

字符串长度没有得到正确的长度,所以程序的其余部分不起作用。我正在尝试每行读取 62 个字符,然后用另外 62 个字符打印一个新行。

谁能帮我正确地将字符数组传递给输出函数?

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

#define _CRT_SECURE_NO_DEPRECATE

void output(char *wbuf, char *lbuf, int lineLength);
void readFile(FILE *getty, char *wbuf, char *lbuf);

FILE *getty;

int main(void) {
    char wbuf[1000] = {0}, lbuf[1000] = {0};

    if (fopen_s(&getty,"getty.txt", "r") != 0 ) 
    {
        printf("Failed to open getty.txt for reading.");
    } else {
        readFile(getty, wbuf, lbuf);
    }

    fclose(getty);
    return 0;
}

void readFile(FILE *getty, char *wbuf, char *lbuf) 
{
    static int lineLength = 62;
    while (!feof(getty)) 
    {
        fscanf(getty, "%s", wbuf);
        output(wbuf, lbuf, lineLength);     
    }
}

void output(char *wbuf, char *lbuf, int lineLength) 
{
    int wbufLength, lbufLength, i = 0;

    wbufLength = strlen(wbuf);
    lbufLength = strlen(lbuf);
    //prints incorrect
    printf("wbuflength %d lbuflength %d\n", wbufLength, lbufLength); 
    // lengths
    if ( (wbufLength + lbufLength) <= lineLength) 
    {                  
        strcat(lbuf,wbuf);  //lbuf should be 0 but it starts at
    }                       //274, wbuf not correct either
    else 
    {
        strcat(lbuf,"\n");
        lineLength += 62;
        strcat(lbuf, wbuf);
    }
}

【问题讨论】:

  • feof 可能不像你想象的那样工作。
  • 专业提示:当feof 返回 false 时,切勿循环,EOF 标志将在 I/O 操作之后设置。
  • 另外,如果你想从文件中获取,总是有fgets
  • 另一个...您的数组未初始化。您确实在声明中初始化它们。
  • 要检查发生了什么,您可能需要在调试器中运行程序,并逐行查看代码以查看实际发生的情况。

标签: c arrays char


【解决方案1】:

问题是你的循环条件:

while (!feof(getty)) { ... }

直到输入操作失败后才会设置EOF标志。

在您的情况下,循环循环,然后 fscanf 操作失败,因为它位于文件末尾但您没有在循环内检查它,然后您调用 output 即使没有读取任何内容从文件中。然后循环继续,然后它注意到文件已经到达 EOF。

【讨论】:

  • 输入循环应检查输入函数返回的结果(在您的情况下为fscanf)。 feof 函数很少有用;它只能告诉你为什么事后没有输入。推荐阅读:comp.lang.c FAQ第12节。
猜你喜欢
  • 2012-11-27
  • 2023-03-06
  • 2021-11-13
  • 1970-01-01
  • 2023-04-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-17
相关资源
最近更新 更多