gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 04:49:21 26 4
gpt4 key购买 nike

字符串长度没有得到正确的长度,因此程序的其余部分无法运行。我正在尝试每行读取 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);
}
}

最佳答案

问题是你的循环条件:

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

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

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

关于c - 将未初始化的字符数组传递给函数。崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17411072/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com