Memory adressing.

Started by
3 comments, last by Dancin_Fool 11 years, 10 months ago
I'm wondering if I'm doing this the right way.

Suppose I have a 16bit data type, short in C, and I want it to represent two characters, 'H' and 'U', in a way, this short would act like a char vector of length 2, char[2].

This is the code:


short hum;
memset(&hum, 0, sizeof(short));
memcpy(&hum+0, "H", sizeof(char));
memcpy(&hum+1, "U", sizeof(char));


I don't know if memory addresses can be handled in this byte by byte approach, ignoring the real data type size, this would be better than using bit shift and OR operator, I believe.

Thanks for the help in advance.
Tiago.MWeb Developer - Aspiring CG Programmer
Advertisement
If I'm not mistaken, using +1 since it's a short the compiler will assume that you want to increment by 2 bytes. What you'd need to do is cast it to a char* and then do the +1 like this

short hum;
memset(&hum, 0, sizeof(short));
memcpy(&hum, "H", sizeof(char));
memcpy(((char*)&hum)+1, "U", sizeof(char));


or you could do something like this


short hum = 0;
char* humPtr = (char*)&hum;
*humPtr = 'H';
*(humPtr+1) = 'U';
I don't know if memory addresses can be handled in this byte by byte approach, ignoring the real data type size, this would be better than using bit shift and OR operator, I believe.

Read up on pointer arithmetic. &hum+1 is the next short if &hum is an array, therefore, &hum+1 is sizeof(short) bytes after &hum. However, ((char*)&hum) + 1 is the next byte after &hum...

Personally, I think using memcpy to copy a single byte from a string is a waste. I'd prefer any one of the following:
1. Directly reinterpreting from a string:

short hum = *(const short*)"HU";

printf( "hum=%d\n", hum );


2. Bit-wise operations

short hum = ('H' << 8) | 'U';

printf( "hum=%d\n", hum );


3. Unions

union {
short hum;
char buf[sizeof(short)];
} _;

_.buf[0] = 'H';
_.buf[1] = 'U';

printf( "hum=%d\n", _.hum );
It's quite confusing since there are only exemples of memset() and memcpy() involving "char" types, so I appreciate the article fastcall22. About the third parameter in both memset() and memcpy(), is it right to assume it's the size of a char and not the size of the data type, so they set or copy n bytes from the pointer specified?
Tiago.MWeb Developer - Aspiring CG Programmer
Yes, it's safe to assume the size parameter is always in bytes.

This topic is closed to new replies.

Advertisement