我正在尝试读取作为指向此函数的指针传递的缓冲区。 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/