Re: alignment



Kies Lee wrote:
main(void)  {
union { char a[10];
            int i;
          } u;
int *p =  (int*)&(u.a[1]);
*p = 17;
}

This would be expected to be quite slow, on current hardware platforms
which can make it work.  Not that you would notice if you did it only
once.  Besides, if it does "work," how can you check that it does the
same thing on all the platforms of interest to you?  I suppose, for many
little-endian platforms, it would set u.a[1] to 17, and zero out
u.a[2..4].  The effect on u.i would depend on what was there before.  On
a long-ago platform I learned on, it would (efficiently) zero out
u.a[0..2], and set u.a[3] and u.i to 17, without affecting u.a[4].
What's the point, other than to check how your platform behaves in odd
situations?  You could do it more efficiently, portably, and readably,
with a simple assignment and a memset().

I don't want to know how it work, but I want to know why it works.

If you learn how it works, you'll also find out why it works -- or not, as the case may be depending on the implementation/host system.


Because the address of the p(pointer) could be 3221217958(one possible
value),
it is not on the edge of the memory(cann't be divided by 4).

<OT> Apart from this being entirely irrelevant, I'm wondering why the fact that X is not divisible by 4 ensures it cannot be on the edge of memory? </OT>

                                                             I don't
know why ?

Neither do I.

--
Kies


Cheers

Vladimir

--
My e-mail address is real, and I read it.
.



Relevant Pages

  • Re: size_t - why?
    ... A char is CHAR_BIT bits, ... An int is at least 16 bits (the minimum value it can hold must ... > small platforms where single objects cannot exceed a certain size, ... All clear now - and thanks for the stds ...
    (comp.lang.c)
  • Re: Binary-mode i/o, width of char, endianness
    ... > The second option is to allocate the input buffer as simply one int ... > object that is guaranteed to be at least 24 bits wide: the long int, ... On platforms such as the kind you are worrying about ... I would stick to unsigned char for this project. ...
    (comp.lang.c)
  • Re: Runtime errors possible when I forgot include
    ... > that is return value is supposed to be int and parameters are converted using ... > If implicit conversion between int and char* is unsafe < ... 64-bit platforms now still have 32-bit int, and then there's still the odd LP32 ...
    (comp.lang.c)
  • Re: Is __int64 dead?
    ... Types char, signed char, and unsigned char are all guaranteed to be 1 byte long on all platforms. ... For my personal tastes, I see long long int, and think something along the lines of "now, what size is int on this platform? ...
    (microsoft.public.vc.mfc)
  • Re: Turn off ZeroDivisionError?
    ... platforms do exactly what I want for division by zero: ... Python doesn't generate exceptions for other floating point ... case of division by zero. ...
    (comp.lang.python)