Because I was trying out different ways of accessing subsections of binary data I was playing around and tried this:
typedef struct structTest {
unsigned char c;
unsigned short s;
unsigned int i;
} Test;
int main(void)
{
char blah[10] = "hello";
void * ptr = blah;
char e;
long l;
memcpy(&e, &ptr[1], sizeof(char));
memcpy(&l, &ptr[1], sizeof(long));
char * s = (char *) &l;
printf("%c %s\n",e,s);
Test t;
t.c = 255;
t.s = 2705;
t.i = 150586;
void * v = (void *) &t;
int i;
short sh;
memcpy(&sh, &v[1], sizeof(short));
memcpy(&i, &v[3], sizeof(int));
printf("%hd, %d\n", sh,i);
return 0;
}
The first bit prints 'e' and 'ello' which is what it was intended to. The second bit doesn't do what was intended.
What I really am not clear about is what the number in the &v[n]
actually refers to, since I'd always imagined what was pointed to by a void pointer as a big blob of data without any kind of internal division. My initial guess (hence the assumption the above would work) is that it would divide it as a byte array. Clearly that was wrong. Also clearly the compiler doesn't complain about me indexing a void pointer even though without a type to define the size it has no real way to tell what size the index refers to. So it must have some understood size? Except if it were simply one size then the first bit wouldn't work unless that size was a byte.
I was thinking maybe the size was defined by the third argument maybe?
Anyone want to help me out?