> > In this example:
> > unsigned char array[100];
> > void *ptr;
> > ptr = &array[0];
> > ptr++;
> Bzzzt! Arithmetic on pointers to objects of unknown size
> isn't permitted. A `void' "object" has no size (not even a
> zero size), so this pointer arithmetic can't be carried out.
> Can't be carried out in C, that is; gcc in non-Standard modes
> (and perhaps other compilers, too) go beyond the bounds of C
> to provide meaning in this case.
> > Is ptr now pointing at array[1]?
> Impossible to say.
> > Since it is a void pointer how does compiler know how many bytes to bump
it
> > up?
> You've identified the difficulty, and the reason why the
> Standard doesn't define pointer arithmetic in this case.
> > I was not sure if I should cast when I do the pointer arithmetic.
> You may have seen things like
> ((unsigned char*)ptr)++;
> ... but this is Bad Old Code: again, it isn't C. What you *can*
> do is
> ptr = ((unsigned char*)ptr) + 1;
> > In may real application I do actually need a void *, because array[]
will
> > contain various
> > data types that I need to extract into different sized variables.
> You can generalize the above to other types:
> unsigned char array[100];
> void *ptr = array;
> char c;
> int i;
> double d;
> c = *((char*)ptr);
> ptr = ((char*)ptr) + 1;
> i = *((int*)ptr);
> ptr = ((int*)ptr) + 1;
> d = *((double*)ptr);
> ptr = ((double*)ptr) + 1;
> ... BUT you may run into alignment problems. For example, if
> the implementation has stricter alignment requirements for
> `int' or `double' than it does for `char', this isn't going
> to work. (Note that array[] itself might not even be aligned
> for such types.)
> Here's a method that overcomes the alignment problems.
> I'm illustrating it with a character pointer instead of with
> a void pointer because I think it's clearer, but you're free
> to use a `void*' if you prefer:
> unsigned char array[100];
> unsigned char *ptr = array;
> char c;
> int i;
> double d;
> c = *ptr++; /* easy case */
> memcpy (&i, ptr, sizeof i);
> ptr += sizeof i;
> memcpy (&d, ptr, sizeof d);
> ptr += sizeof d;
> --
Your example is exactly what I want to do. I did not think of