3

I'm trying to store some integers in a queue, which queue is basically a fixed size char array storing integers (or every value) byte by byte:

class fixed_size_queue{
    char *buffer;
    unsigned int head;
    int tail;
    q_typeinfo   tinfo;
public:
    fixed_size_queue(q_typeinfo tinfo_):tinfo(tinfo_) { 
    buffer = new char[MAX_SIZE*tinfo.get_size()];
    head = 0;
    tail = -1;
    }
    char* pop() {
    char* value = buffer+head;
    head++;
    return value;
    }
    void push(char* value) {
    tail++;
    buffer[tail] = *value;
    cout<<"pushing value = "<<(int)*value<<endl; //line 22
    }
};

When trying to push values to this queue, I use:

void push_q(void* value){
    q.push(value);
}

With the above, if I push values from 0 to 127, they are pushed and popped correctly. If I push value 128, at line 22, it outputs "pushing value -128". Pushing 129 outputs -127 and goes on until it reaches 127 again and wraps around.

The size for each integer is 8 in the queue's array (I'm rounding it up due to some reasons) but I've tried with 4 and the same strange error appears.

I have also tried using reinterpret_cast, to cast and copy "value" to a char* when pushing or popping the values but the same thing happens. Does anyone find something wrong? Thank you!

--Update: Finally, the problem was not the type. I just wanted to store the bytes of any variable. For example, an integer should be split into (4)char-bytes and be stored in the array. What was needed was a copy of the integer's data to the char array! This above, didn't work because only one byte was copied every time. Also increments of head and tail should be +=sizeof(int).

Kallia Chro
  • 35
  • 1
  • 6

2 Answers2

0

You should use unsigned char rather than char, and all will be fine.

Of course, if you are actually storing values beyond 255 - or want to store negative values - you will need to do something more than what you have shown above.

Mats Petersson
  • 126,704
  • 14
  • 140
  • 227
0

What you are seeing is the effect of storing your data in a a char data type - which is typically a signed value which can hold values from -127 to +127 (you would expect -128, but that is apparently the C++ spec.

Take a look at this SO question size-of-int-long-etc and use your knowledge of your application to decide what datatype your should be using.

Community
  • 1
  • 1
Peter M
  • 7,309
  • 3
  • 50
  • 91