Reputation: 422
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:
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?
Upvotes: 3
Views: 902
Reputation: 222650
foo((uint8_t []) { 0x01 }, 1);
The form “(
type ) {
initializers… }
” is a compound literal, specified in 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
. As an array, it is automatically converted to a pointer to its first element, which is suitable for the first parameter of 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.
Upvotes: 2