1

I am trying to use std::vector as a memmory buffer:

int main( )
{
    int i = 0x01020304;
    size_t size = sizeof(int);
    std::vector<char> data;

    data.insert( data.end(), (char*)&i,  (char*)(&i  + size) );

    for ( int i = 0; i < data.size(); ++i){
        std::cout << int(data[i]) << std::endl;
    }

    return 0;
}

I am expecting output 4 3 2 1

But I got

4
3
2
1
51
73
-107
81
-9
127
0
0
36
-7
84
-50

Can some one explaing what I am doing wrong?

0

3 Answers 3

2

size is in bytes, so you need to increase the char*, not int*.

data.insert( data.end(), (char*)&i,  (char*)(&i)+size );
Sign up to request clarification or add additional context in comments.

1 Comment

@Jeka Then please award the answer, so that it's crystal clear for others reading this question in future.
2

Just to add to other questions, when you avoid code duplicate and make it more readable you also avoid some mistakes:

int i = 0x01020304;
std::vector<char> data;
char *begin = reinterpret_cast<char *>( &i );

data.insert( data.end(), begin,  begin + sizeof(i) ) );

you probably would need to work with different types:

template<typename T>
void insertData( std::vector<char> &data, T value )
{
    char *begin = reinterpret_cast<char *>( &value );
    data.insert( data.end(), begin,  begin + sizeof(value) ) );
}

Comments

1

With (char*)(&i + size) you increase a pointer to int instead of a pointer to char. Since size seems to be 4 in your case you find yourself adding the data of 4 ints instead of 4 chars.

auto cp = reinterpret_cast<char*>(&i);
data.insert( data.end(), cp,  cp  + size );

1 Comment

I got an error C2440: 'static_cast' : cannot convert from 'int *' to 'char *' Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast But works fine with reinterpret cast

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.