1

I currently send commands over spi as follows:

I want to create a function to send any command passed to it. Can I pass a byte array as an argument to function? Like I have below.

1
  • You cannot pass an array to/from a function in C. But you can pass a pointer to its first element. Commented Feb 29, 2016 at 12:43

1 Answer 1

2

Passing arrays is done using pointers in C.
Since arrays may decay to pointers through an implicit conversion from T[] to T*, we pass a pointer to the function referring to the array.

Write the function like1

void sendCommand(uint8_t* Cmd) {
    ...
}

and call it like

sendCommand(SyncCmd);

However, watch out: sizeof(Cmd) yields the size of the pointer, not the whole array, when used within sendCommand. Therefore, you need to pass the size explicitly. See this by Linus Torvalds to hear some harsh words on this matter.


1 Note that uint8_t[], uint8_t*, uint8_t[42], and friends are all equivalent when used as parameters. That is, these are all equivalent:

void foo1(uint8_t*);
void foo2(uint8_t[]);
void foo3(uint8_t[42]);

Thanks to @Olaf for your contribution here.

Sign up to request clarification or add additional context in comments.

3 Comments

uint8_t cmd[] works very well, too. It is more clear that is is use as an array internally - self-documenting code.
@Olaf Hmm, well, that's your perception. The fact that the pointer references an array should also be apparent when reading through the surrounding code. Also, what if someone really passed just one element as cmd with size 1? I prefer uint8_t*. But I'll mention their equivalence, yes. Linus also has a say regarding this and the kernel, only if you're interested.
I read Linus rant now. I fully agree with him that people should learn and know C. But that implies they are aware of the formal array argument conversion. They already have to know the actual array argument decays to a pointer, so the format argument decaying, too should be clear. If you rely on a specific size for an array argument, you have to pass that size (maybe the main problem is the [] syntax). Either as a constant or VLA. The function header should document the arguments ()inconjunction with e.g. Doxygen comments. Requiring reading the code to understand the interface is just bad

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.