1

How can I get length of array which is array of unsigned char*?

This is my array:

unsigned char ot[] = { 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x77, 0x6f, 0x72, 0x6c, 0x64, 0x0, 0x0, 0x0, 0x0, 0x0 };

I tried to use strlen() like this: int length = strlen((char*) ot);

It returns me length of 11 till first 0x0, but what is my array changes to this? (check last element)

unsigned char ot[] = { 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x77, 0x6f, 0x72, 0x6c, 0x64, 0x0, 0x0, 0x0, 0x0, 0xa1 };

Then I get still 11 elements, how can I get "real" length of whole array? Like what if there will be data after some 0x0 element.

For example for:

unsigned char* file_buffer = new unsigned char[BUFFER_SIZE];
fread(file_buffer,sizeof(unsigned char),BUFFER_SIZE,input_file)

What could be best solution? Because return value of fread() can vary, if I am reading last chunk of file, and what if in file will be 0x0 before some data?

tomsk
  • 967
  • 2
  • 13
  • 29

2 Answers2

3

How can I get length of array which is array of unsigned char* ?

According to the examples you gave you are attempting to retrieve the length of an array [] and not an array *. This can be achieved using the keyword sizeof (sizeof(ot)).

However when it comes to pointers (such as your unsigned char *), you will need to know the size beforehand as using sizeof over it would return the allocated size of the pointer itself and not the actual content size of this pointer.

Ra'Jiska
  • 979
  • 2
  • 11
  • 23
  • Thanks, I updated question for `unsigned char*` too. – tomsk Nov 09 '19 at 17:11
  • @tomsk When it comes to `unsigned char *` you cannot know the size of it by just looking at its content (unless you use some unique termination byte, such as the null byte used in c-style strings). The only way to know the size of the buffer is to save the size of it when allocating the buffer and passing it to your functions along the buffer pointer (this can be achieved either by passing a pointer and an integer or a structure holding both your variables). – Ra'Jiska Nov 09 '19 at 17:14
2
unsigned char ot[] = {0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x77, 0x6f, 0x72, 0x6c, 0x64, 0x0, 0x0, 0x0, 0x0, 0x0};

int _length = strlen((char *) ot);
printf("%d\n", _length); // 11

int length = sizeof(ot) / sizeof(unsigned char);
printf("%d\n", length); // 16

// reason behind strlen behaves like this

if (0x0 == '\0') {
    printf("Yes\n");
}

strlen() returns string length when it finds null terminator which is '\0'. If you run the code, it will print Yes at the end, means 0x0 is actually equivalent to '\0' null terminator.

Use sizeof() to get the real length.

Roy
  • 1,189
  • 7
  • 13