结构保持价值

时间:2015-09-15 10:58:49

标签: c++ struct

我正在尝试实现一个结构来保存二进制数据。就像这样:

struct Buffer {
    int size_;
    int capacity = 1000000;
    int beg_index, end_index;
    char data_[1000000];
} buffer_audio[3];

一个在缓冲区中写二进制数据的函数:

int writing_bufer(Buffer buffers, const char *data, int nbytes) {
    if (nbytes == 0) return 0;

    int capacity = buffers.capacity;
    int bytes_to_write = std::min(nbytes, capacity - buffers.size_);

    if (bytes_to_write <= capacity - buffers.end_index)
    {

        memcpy(buffers.data_ + buffers.end_index, data, bytes_to_write);
        buffers.end_index += bytes_to_write;
        if (buffers.end_index == capacity) buffers.end_index = 0;
    }
    else { return 0; }  

    buffers.size_ += bytes_to_write;
    return bytes_to_write;
}

但问题是..每次运行此例程时,都会删除beg_indexend_index的值。 memcpy将覆盖。 例程:

void buffering_mem(char* chunk,int size_chunk, int close_file, int client, int total_size){

    int check_bytes = writing_bufer(buffer_audio[client], chunk, size_chunk);
    //other code

}

1 个答案:

答案 0 :(得分:6)

int writing_bufer(Buffer buffers, const char *data, int nbytes)

应该是

int writing_bufer(Buffer& buffers, const char *data, int nbytes)

您将缓冲区复制到函数中并填充了本地缓冲区,然后销毁它们。