I am getting results from a routine which are unexpected from me.
here is athe code.

void MyTestFunc(){

    u_char MyTest_u_char[10] = {'a','b','c','d','e','f','g','h','i','j'};

    u_char * MyTest_u_char2 = new u_char[8];

    memcpy(MyTest_u_char2,&MyTest_u_char[1],sizeof(u_char)*8);

    int raw_len = sizeof(MyTest_u_char2) + 1;

    string std_str(MyTest_u_char2, MyTest_u_char2 + raw_len);

    cout << std_str << endl; // expecting bcdefghi . getting bcdef
}

Expected output
bcdefghi

Output
bcdef

No matter if I try to copy 8,9 or ten bytes, I only get 5 converted to std::string

Can anyone see my error?

Recommended Answers

All 5 Replies

int raw_len = sizeof(MyTest_u_char2) + 1;

That line is wrong -- sizeof takes the size of a pointer, not the number of bytes allocated to the pointer. In this case sizeof(any pointer) is 4 (in most implementations today but could be some other value depending on your compiler). What you want is the const 8. Better to declare a const int for that and use it throughout so that you don't have to repeat magic numbers all over your program.

Duh! I could not see the forest for the trees.
Thank you kindly.

Incidentally, I thought sizeof would give the size of whatever type was given to it
be that an int pointer or a double type.

Thanks again, corrected line int raw_len = sizeof(u_char) * _EIGHT_;

Incidentally, I thought sizeof would give the size of whatever type was given to it
be that an int pointer or a double type.

It does -- all pointers have the same size.

sizeof(u_char)

You don't need that part because char and uchar are always guaranteed to be 1.

Ah, I see, so would only need that if the type might alter dynamically?

It does -- all pointers have the same size.

Between object pointers an function pointers, all bets are off. But even for different pointers to object types it's not guaranteed that the sizes are the same. Though you've very likely only worked with systems where pointer size matches the address size for all object types (16-bit, 32-bit, 64-bit, etc...) since that's by far the most common.

Further, I can't think of any good reason to assume the size of a pointer or that all pointer sizes are equal. Any code that needs to make such assumptions would probably be very poorly designed, in my opinion.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.