[英]How to convert an integer to a uint8_t pointer?
I have a function defined like: 我有一个定义如下的函数:
void foo(uint8_t *val, int num)
{
for(int i=0;i<num;i++)
printf("Buffer[%i]=0x%X \n",i,val[i]);
}
As a global variable, I have an array declared as: 作为一个全局变量,我有一个声明为:
uint8_t Buffer[4] = {0x01, 0x02, 0x03, 0x04};
So in order to print the buffer, I do the following: 因此,为了打印缓冲区,我执行以下操作:
int main()
{
foo(Buffer,4);
return 0;
}
Which gives as a result: 这给出了结果:
Buffer[0]=0x1
Buffer[1]=0x2
Buffer[2]=0x3
Buffer[3]=0x4
The thing is that, for a particular case, I need to send only one uint8_t parameter to that function replacing the buffer, so I implemented it like: 问题是,对于特定情况,我只需要向该函数发送一个uint8_t参数来替换缓冲区,所以我实现了它:
int main()
{
uint8_t READ_VAL[] = {0x01};
foo(READ_VAL,1);
return 0;
}
Anyway, is there any way to do it inline? 无论如何,有什么方法可以内联吗? I tried to do it like 我试着这样做
foo((uint8_t *)0x01,1);
but it is not working (gives me Segmentation fault error). 但它不起作用(给我分段错误错误)。 Any idea how can I do it? 不知道怎么办呢?
foo((uint8_t []) { 0x01 }, 1);
The form “ (
type ) {
initializers … }
” is a compound literal , specified in C 2018 6.5.2.5. 形式“ (
type ) {
initializers ... }
”是复合文字 ,在C 2018 6.5.2.5中规定。 It creates an object of the specified type with the value given by the initializers. 它使用初始化程序给出的值创建指定类型的对象。
(uint8_t []) { 0x01 }
creates an array of one uint8_t
with value 0x01
. (uint8_t []) { 0x01 }
创建一个值为0x01
uint8_t
数组。 As an array, it is automatically converted to a pointer to its first element, which is suitable for the first parameter of foo
. 作为一个数组,它会自动转换为指向其第一个元素的指针,该元素适用于foo
的第一个参数。
A compound literal inside a function is temporary, with automatic storage duration associated with its enclosing block. 函数内的复合文字是临时的,自动存储持续时间与其封闭块相关联。 A compound literal outside a function endures for the execution of the program, with static storage duration. 函数外部的复合文字用于执行程序,具有静态存储持续时间。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.