gpt4 book ai didi

c - 在文件读取中添加 null 的位置

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

将文件读入 char * 时,应该在哪里添加 null,为什么?选项1或选项2,似乎都可以编译。

char* load_file(char const* path)
{
char* buffer = 0;
long length;
FILE * f = fopen (path, "rb");

if (f)
{
fseek (f, 0, SEEK_END);
length = ftell (f);
fseek (f, 0, SEEK_SET);
buffer = (char*)malloc ((length+1)*sizeof(char));
if (buffer)
{
fread (buffer, sizeof(char), length, f);
}
fclose (f);
}
buffer[length] = '\0'; //option1
buffer[length+1] = '\0'; //Option2
return buffer;
}

最佳答案

通过 malloc 调用,您分配一个 length + 1 个字符的“数组”,索引从 0length(包含)。因此正确的选项只能是“option1”。

关于c - 在文件读取中添加 null 的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48702392/

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