I'm trying to determine array length of msg
on the below code. I used strlen
and sizeof
but they don't return 6. What function can I use to determine the length of uint8_t
array or how can I modify the below code (osal_DataLenght()
func)?
int osal_DataLength( char *pString ){
return (int)( strlen( pString ) );
}
void setNewLevel( uint8_t newLevel ){ //GW specific
uint8_t msg[8] = {'\0'};
msg[0] = '0';
msg[1] = '7';
msg[6]= newLevel;
//msg[7] = '0';
printf("the array length:%d\n", osal_DataLength(msg) );
}
int main(void){
setNewLevel(0xD5);
return 0;
}
sizeof(uint8_t*) is the size of pointer. Which is typically 4 for 32-bit architectures and 8 for 64-bit architectures.
The first array declaration for array1 creates an array of 6 elements, each element being a distinct uint8_t. This is an uninitialized array, you should assume that the values in the array are some random garbage junk values. Do not assume that uninitialized variables have a 0 value - they almost certainly will not!
sizeof(uint8_t *) is 8 size of pointer. The size of the pointer depends on the target platform and it's usually 8 bytes on x64, 4 bytes on 32 bit machines, 2 bytes on some 16 bit microcontroller, etc.
To know the size of your array, write (in setNewLevel()
as said @Dabo) :
sizeof(msg)/sizeof(uint8_t);
strlen()
returns the size of a string (char array terminated by NULL
, ie '\0'
). You CAN'T use it in this context, since :
msg[2]
to msg[5]
values are not initializedmsg
is not a char
sequence terminated by NULL
.When passing array to a function it decays to a pointer, and there is no way in function to know the length of your original array. Pass the length as additional variable
int osal_DataLength( char *pString, int size )
.
.
.
printf("the array length:%d\n", osal_DataLength(msg, sizeof(msg)) );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With