20

I may be wrong in my definition of what a literal array is. I am refering to the following as one:

{0x00, 0x01, 0x03}

I have a function that accepts an array as shown below:

void mote(char arry[]){}

When I am calling this function I would like to be able to do the following:

mote({0x00, 0x01, 0x03})

However my compiler(C30) complains with the following error:

error: syntax error before '{' token

I also tried the above with these brackets -> [ ] but i still get the same error.

My questions

1) Is it possible to pass a literal array into a function?

2) If yes, how?

Thank you all in advance

2 Answers2

34

This syntax is called array initializer. Therefore, it can be used only when you define your array.

C11 (n1570), § 6.7.9 Initialization

initializer:
    assignment-expression
    { initializer-list }
    { initializer-list , }

However, in C99, it is possible to do it with compound literals:

mote((char[]){0x00, 0x01, 0x03});
md5
  • 23,373
  • 3
  • 44
  • 93
  • 3
    Note: If the function can be made to take `const char arry[]` (likely, since the mere fact of passing a compound literal implies the caller doesn't need the result, so unless the function is using it as scratch space, it should be possible to make it `const`), passing `(const char[]){0x00, 0x01, 0x03}` allows the compiler to use static storage (baked into binary's constants section) shared with string literals; without the `const` (and on compilers that don't merge w/string literals), outside global scope, the literal would be reconstructed on each use (it only has automatic storage duration). – ShadowRanger Jan 31 '20 at 17:35
9

if C99 is not supported, try this one:

char cp[] = {0x01, 0x02, 0x03};
mote (cp);
Stephen Reindl
  • 5,659
  • 2
  • 34
  • 38