Sign in to follow this  

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

This topic is 1277 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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 this post


Link to post
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 this post


Link to post
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.

Share this post


Link to post
Share on other sites

This topic is 1277 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this