2

I have an array that's used in a communication protocol (a USB device descriptor). This protocol calls for the array size in the array header. So I would like to do that (which is forbidden):

static uint8_t array[]= {
    TYPE,
    sizeof(array),
    other data...
};

The array being in a read only part of the memory, I can't override the relevant cell after the fact, and I'm not really willing to copy it to override the cell (it's in a minimal embedded system). I need it to look like "on the wire" because it will go through DMA.

Is there some kind of magic that could work around this limitation? I'm willing to use C99 or GNU extensions. I won't switch just for that, but I'm curious about a C++ solution too.

3
  • 1
    And specifying the size of the array in the declaration, e.g. as static uint8_t array[18] = ... is presumably no more helpful a solution than 'why don't you just type the size of the array by hand and not use sizeof'? Commented Apr 29, 2013 at 19:34
  • "The array being in a read only part of the memory" It can't be unless you omitted a const. Commented Apr 29, 2013 at 19:39
  • @danielFischer good catch, thanks. But with or without the 'const' this stuff ends up in a locked part of the memory map. Commented Apr 29, 2013 at 19:58

1 Answer 1

3

If you would not use an array, but a struct, which it looks like you really want, then it would be possible:

typedef struct
{       int     type, size, other;
} pack_t;
static pack_t a =
{       10, sizeof(a), 11
};
Sign up to request clarification or add additional context in comments.

3 Comments

here is the result: gist.github.com/nraynaud/5484759 I tink the line count is high, do you see a more compact way to do it? It's too bad I can't use the '=' directly in the struct.
You could of course lose the field names, but that doesn't aid to the readability. If you have to make many of those descriptors, I would make a macro filling in most of the standard values and taking the varying ones from the macro parameters.
With GCC you'll likely want to add __attribute__((packed)) to the definition of your struct, just to make absolutely sure there's no padding.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.