Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine array length of uint8_t?

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;
}
like image 996
sven Avatar asked Apr 16 '15 11:04

sven


People also ask

What is size of uint8_t C++?

sizeof(uint8_t*) is the size of pointer. Which is typically 4 for 32-bit architectures and 8 for 64-bit architectures.

Is uint8_t an array?

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!

What does sizeof uint8_t return?

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.


2 Answers

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 :

  1. msg[2] to msg[5] values are not initialized
  2. msg is not a char sequence terminated by NULL.
like image 183
Amessihel Avatar answered Sep 18 '22 07:09

Amessihel


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)) );
like image 33
Dabo Avatar answered Sep 18 '22 07:09

Dabo