c - 修改作为指针传递的缓冲区

标签 c pointers malloc memcpy

我正在尝试读取作为指向此函数的指针传递的缓冲区。 memcpy() 工作正常,数据正确存储在 buffer 中,但是当我在函数之外访问 buffer 时,它是 null 。有一些指针问题我没有到这里。

这是代码,我取出了大部分,我知道它正确地复制了数据,但它没有将它传递给 buffer 指针。想法?

int read(file file, char *buffer , int maxlen) {
    int bytes_read;

    // copy data to file buffer
    bytes_read = min(maxlen, file->file_size - file->cursor);
    buffer = (char*) malloc(bytes_read);

    memcpy(buffer , file->buffer + file->cursor, bytes_read);

    return bytes_read;
}

最佳答案

问题很简单:你正在修改变量“buffer”。由于它是按值而不是按引用传递的,因此调用函数看不到更改。为了使对缓冲区的更改可见,您需要传入一个指向缓冲区的指针。

你的函数看起来像这样:

int read(file file, char **buffer , int maxlen) {
    int bytes_read;

    // copy data to file buffer
    bytes_read = min(maxlen, file->file_size - file->cursor);
    *buffer = (char*) malloc(bytes_read);

    memcpy(*buffer , file->buffer + file->cursor, bytes_read);

    return bytes_read;
}

调用函数:

rv = read(file, &buffer, maxlen);

关于c - 修改作为指针传递的缓冲区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20589045/

相关文章:

c - 无法初始化结构数组

c - 在主函数中返回变量

c - 通过引用将静态二维结构数组传递给函数

c++ 对 vector 问题的引用?

c - 不使用 malloc/str 方法将结构转换为 unsigned char 数组

c++ - 除了 boost::pool 之外,C++ 中的自定义池分配器

c++ - R包错误错误: ‘std::Rf_beta’ has not been declared #define beta Rf_beta

c - 执行 x87 FPATAN 操作的扩展 GCC 内联汇编中的 clobber 列表的说明

c - 使用malloc动态创建字符串数组

c - 在C中添加大量数字