【问题标题】:How to null terminate pointer passed as an argument如何使作为参数传递的指针为空终止
【发布时间】:2021-03-29 18:04:35
【问题描述】:

所以我有这个函数来读取文件,分配内存,并将文件的内容放入缓冲区。我最后总是得到垃圾数据,所以我需要一种方法来终止缓冲区。

#include "GetText.h"

void GetText(const char* filename, char** buffer)
{
    FILE* file = fopen(filename,"rb");
    long file_lenght;

    if(file)
    {
        fseek(file, 0, SEEK_END);
        file_lenght = ftell(file);
        rewind(file);

        *buffer = (char*) malloc(file_lenght + 1);

        fread(*buffer, 1, file_lenght, file);

        *buffer[file_lenght] = '\0'; //This line crashed program

        fclose(file);
    }
}

【问题讨论】:

  • 试试(*buffer)[file_lenght] = '\0';
  • 如果您返回指针char* GetText(const char* filename) { buffer = (char*) malloc(file_lenght + 1); ... return buffer; },代码将更容易理解(和编写)。不需要双指针。
  • 如果您使用 C++ 样式代码而不是 C 样式代码 std::string GetText(...) { ... } 会更容易使用 std::string 将为您完成所有艰苦的工作,尤其是正确释放分配的内存的工作。
  • 或者试试*(buffer + file_length) = '\0'
  • 最后是C++C ?

标签: c++ c pointers


【解决方案1】:

由于括号运算符的优先级高于指针取消引用,因此您需要在索引之前取消引用 缓冲区,如下所示:

(*buffer)[file_lenght] = '\0';

在您的程序中,您还需要确保 malloc 是成功的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-29
    • 2021-10-15
    • 2012-01-24
    • 1970-01-01
    • 1970-01-01
    • 2012-11-28
    • 2018-05-14
    相关资源
    最近更新 更多