将未初始化的字符数组传递给函数。崩溃

时间:2013-07-01 18:20:17

标签: c arrays char

字符串长度未获得正确的长度,因此程序的其余部分不起作用。我试图读取每行62个字符,然后用另外62个字符打印一个新行。

任何人都可以帮我正确地将char数组传递给输出函数吗?

#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);
    }
}

1 个答案:

答案 0 :(得分:0)

问题在于你的循环条件:

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

输入操作失败后,之前不会设置EOF标志。

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