gpt4 book ai didi

c - c 中的声明错误

转载 作者:行者123 更新时间:2023-11-30 18:42:49 28 4
gpt4 key购买 nike

我正在编写一个程序来读取文件。我一直遇到运行时错误,具体取决于我是否放置 int i在main函数的第三行。

我认为它没有理由对我的程序产生影响。但确实如此。那么为什么会发生这种情况呢?而且,至少在原则上,我们不应该能够在任何我们想要的地方声明变量吗?

这是我的代码

得到答案

故事的寓意:在使用指针之前始终初始化它们。

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

char read_char(FILE ** fp);

int main()
{
char * str;
str = (char *) malloc(sizeof(char));

FILE * f;
// int i <---------Problem here

f = fopen("txt.txt", "r");

*str = read_char(&f);
putchar(*str);

return 0;
}


char read_char(FILE ** fp)
{
char * c;
c = malloc(sizeof(char));

if ((*fp) == NULL)
{
printf("Error accessing file");
exit(0);
}

(*c) = getc((*fp));
return((*c));
}

最佳答案

您已定义

 char * str;

你已经使用了它

*str = read_char(&f);

str尚未指向内存空间

*str 表示内存空间中的第一个字节(str 指针所指向的位置)的内容将由 返回的 char 值填充>read_char() 函数

事实上,你所做的是一种未定义的行为。所以添加 i 定义给出了一种行为。删除 i 定义给出另一种行为

在你的代码修复之后

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

char read_char(FILE *fp);

int main()
{
char * str = malloc(sizeof(char));
FILE * f;
int i;

f = fopen("txt.txt", "r");

*str = read_char(f);
putchar(*str);

return 0;
}


char read_char(FILE * fp)
{
char c;

if (fp == NULL)
{
printf("Error accessing file");
exit(0);
}

c = getc(fp);
return c;
}

关于c - c 中的声明错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14401223/

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