简体   繁体   English

将数组作为函数参数c

[英]passing array as function argument c

I currently send commands over spi as follows: 我目前通过spi发送命令,如下所示:

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. 就像我下面。

Passing arrays is done using pointers in C. 传递数组是使用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. 由于数组可能会通过从T[]T*的隐式转换而衰减为指针,因此我们将指针传递给引用该数组的函数。

Write the function like 1 编写类似1的函数

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 . 但是 ,请注意:在sendCommand使用sizeof(Cmd)产生指针大小,而不是整个数组大小 Therefore, you need to pass the size explicitly. 因此,您需要显式传递大小。 See this by Linus Torvalds to hear some harsh words on this matter. 请看Linus Torvalds的这篇文章 ,以听取一些苛刻的话。


1 Note that uint8_t[] , uint8_t* , uint8_t[42] , and friends are all equivalent when used as parameters. 1注意,用作参数时, uint8_t[]uint8_t*uint8_t[42]和朋友都是等效的。 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. 感谢@Olaf在这里的贡献。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM