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].
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.
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));
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";
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?