0

I need to allocate an integer array in stack in my function, how can I make it 32 bits aligned?

void f1() {
    uint8_t slope[4*32];
}

I am running on linux.

Kevin
  • 53,822
  • 15
  • 101
  • 132
michael
  • 106,540
  • 116
  • 246
  • 346
  • Related: [GCC __attribute__((aligned(x)) explanation](http://stackoverflow.com/q/841433/464709). – Frédéric Hamidi Feb 13 '14 at 19:30
  • What architecture? x86_64 has stack aligned on 16-byte boundary, so what you are after is there out of the box. –  Feb 13 '14 at 19:31
  • 2
    If you define the array in the type you use it for, it will be aligned as required in the C implementation. E.g., if you define the array as `uint32_t slope[32];`, it will be aligned as needed. Attempting to align the array more than is regularly needed by the C implementation should be done only in special situations. What specifically is the larger problem you are attempting to solve? – Eric Postpischil Feb 13 '14 at 19:38
  • 1
    **Why** exactly **do you need that?** Be precise and specific please (and edit your question)! – Basile Starynkevitch Feb 13 '14 at 19:46

1 Answers1

0

This should work across most (all?) architectures and doesn't require compiler-specific techniques, although I will admit to not being sure what the implications of this declaration being local versus global/file-scope.

void f1(void)
{
    union
    {
        uint32_t align;
        uint8_t  arr[4*32];
    }   slope;

    /* can now be access via slope.arr[] */
}
Ryan
  • 185
  • 11
  • 3
    This does not actually guarantee 32-bit alignment. It guarantees the alignment required in the C implementation for the `uint32_t` and `uint8_t` types, which is not necessarily 32 bits. (This is likely sufficient for what the OP needs, but it is not what they ask for.) – Eric Postpischil Feb 13 '14 at 19:36
  • I should also have mentioned that my answer requires a C99 compliant compiler. I thought uint32_t is required to be exactly 32 bits in width by the standard. Is it still allowable for this to be allocated on a 16-bit boundary? – Ryan Feb 13 '14 at 19:41
  • 1
    The standard does specify that `uint32_t` must be exactly 32 bits, but it does not specify any alignment requirements for it. – Eric Postpischil Feb 13 '14 at 19:43