2017-01-20 9 views
-2

C++で循環バッファを書くときに問題があります。ここでは、現時点での私のコードベースは、次のとおりです。C++:循環バッファの問題

circ_buf.h:

#ifndef __CIRC_BUF_H__ 
#define __CIRC_BUF_H__ 


#define MAX_DATA (25) // Arbitrary size limit 

// The Circular Buffer itself 
struct circ_buf { 
    int s;    // Index of oldest reading 
    int e;    // Index of most recent reading 
    int data[MAX_DATA]; // The data 
}; 

/*** Function Declarations ***/ 
void empty(circ_buf*); 
bool is_empty(circ_buf*); 
bool is_full(circ_buf*); 
void read(circ_buf*, int); 
int overwrite(circ_buf*); 


#endif // __CIRC_BUF_H__ 

circ_buf.cpp:

#include "circ_buf.h" 


/*** Function Definitions ***/ 

// Empty the buffer 
void empty(circ_buf* cb) { 
    cb->s = 0; cb->e = 0; 
} 

// Is the buffer empty? 
bool is_empty(circ_buf* cb) { 
    // By common convention, if the start index is equal to the end 
    // index, our buffer is considered empty. 
    return cb->s == cb->e; 
} 

// Is the buffer full? 
bool is_full(circ_buf* cb) { 
    // By common convention, if the start index is one greater than 
    // the end index, our buffer is considered full. 
    // REMEMBER: we still need to account for wrapping around! 
    return cb->s == ((cb->e + 1) % MAX_DATA); 
} 

// Read data into the buffer 
void read(circ_buf* cb, int k) { 
    int i = cb->e; 
    cb->data[i] = k; 
    cb->e = (i + 1) % MAX_DATA; 
} 

// Overwrite data in the buffer 
int overwrite(circ_buf* cb) { 
    int i = cb->s; 
    int k = cb->data[i]; 
    cb->s = (i + 1) % MAX_DATA; 
} 

circ_buf_test.cpp:

#include <iostream> 
#include <fstream> 
#include <string> 
#include <cstdlib> 
#include "circ_buf.h" 


int main(int argc, char** argv) { 
    // Our data source 
    std::string file = "million_numbers.txt"; 
    std::fstream in(file, std::ios_base::in); 

    // The buffer 
    circ_buf buffer = { .s = 0, .e = 0, .data = {} }; 

    for (int i = 0; i < MAX_DATA; ++i) { 
     int k = 0; in >> k; // Get next int from in 
     read(&buffer, k); 
    } 

    for (int i = 0; i < MAX_DATA; ++i) 
     std::cout << overwrite(&buffer) << std::endl; 
} 

主な問題はIバッファを取得して配列に整数を書き込んでいます。メインプログラム(circ_buf_test)をコンパイルして実行すると、印刷すると予想されるものではなく、同じ番号が25回だけ印刷されます(数字1〜25 - "million_numbers.txt"は文字通り数字1〜1000000です) 。これが重要な場合に備えて、番号は2292656です。

ここで間違っている可能性がある人はいますか?

+1

*メンバー関数*はこれまでに聞いたことがありますか? –

+0

'__CIRC_BUF_H__'は連続したアンダースコアを含んでいるため、実装のために予約されている識別子です。あなたは別のヘッダーガードを考え出すべきです。 'CIRC_BUF_H_'はOKです。 – user2079303

+0

@ user2079303します。推奨していただきありがとうございます。 – MrM21632

答えて

1

あなたの関数overwrite(circ_buf* cb)は何も返しません(本体にreturnはありません)。私はあなたが(コンパイルログにこの「主な問題」の理由を見つけるのラインが「警告」で起動見ることができます期待してい

for (int i = 0; i < MAX_DATA; ++i) 
     std::cout << overwrite(&buffer) << std::endl; 

:だから何かを印刷することができます値の印刷用のコードは、(「未定義の動作」を参照してください) )。このように修正できます:

int overwrite(circ_buf* cb) { 
    int i = cb->s; 
    int k = cb->data[i]; 
    cb->s = (i + 1) % MAX_DATA; 
    return k; 
} 
+0

うわー、私はそれが行方不明のために愚かな気がします。ありがとう。 – MrM21632

関連する問題