Why does this code snippet not work when i take it out of function scope

Recommended Posts

I saw in beej network guide some code that packs a int into a char and I didnt understand some things about it so I was just playing around with it and for one reason or another I moved the snippet directly into main. I found out it doesn't work right when I do that. Notice it outputs a really big number if I do the operations of the pack functions in main. Any particular reason why?


#include <iostream>
#include <bitset>
#include <limits>
using namespace std;

void packi32(unsigned char *buf, unsigned long i)
{
*buf++ = i>>24;
*buf++ = i>>16;
*buf++ = i>>8;
*buf++ = i;

//cout << buf[0] << " " << buf[1] << " " << buf[2] << " " << buf[3] << endl;
}

unsigned long unpacki32(unsigned char *buf)
{
return (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
}

int main()
{
unsigned char * buf = new unsigned char[4];
unsigned long i = 254;
unsigned long result = 0;

*buf++ = i >> 24;
*buf++ = i >> 16;
*buf++ = i >> 8;
*buf++ = i;

result = unpacki32(buf);
cout << result << endl;

memset(buf, 0, sizeof(buf));

packi32(buf, i);
result = unpacki32(buf);

cout << result;

cin.get();
}



Share on other sites
1. If you need an array of a small number of chars, I would default to putting them on the stack, i.e. "unsigned char buf[4]", instead of using new. Your sizeof would work if you did that.

2. If you want to test your function's ability to pack and unpack an int into a char array, you might want to choose an int that actually takes more than one byte to store.

Share on other sites

1. If you need an array of a small number of chars, I would default to putting them on the stack, i.e. "unsigned char buf[4]", instead of using new. Your sizeof would work if you did that.

You could also use std::array for a fixed size array.  That makes it much harder to forget to release the dynamic memory, and sizing should work properly there too.  But I agree, for small stuff like this, stack allocation would probably be fine.

Create an account

Register a new account

• Partner Spotlight

• Forum Statistics

• Total Topics
627676
• Total Posts
2978582

• 11
• 12
• 10
• 12
• 22