1

let say I have a char pointer like this:

unsigned char* value="Hello\0Hello";

how can i calculate the size of value, as strlen only calculate the size of string until the '/0' so I can not use strlen, and also sizeof returns the length of the pointer itself so is there any way to calculate the length of the value?

Lia
  • 33
  • 6
  • What tells how lot of mid way null characters it has (if any)? Can't you use array like ... unsigned char value[] =? – Öö Tiib May 30 '22 at 06:29
  • @ÖöTiib no the structure of my program is in a way that i can not use array and it should be pointer. – Lia May 30 '22 at 06:34
  • @Lia And what about the first question? Plain pointer to first character is not enough information when string contains null characters as the whole string is also terminated with null character. – Öö Tiib May 30 '22 at 06:38
  • @Lia where exactly is your string pointer coming from, and why does the data have nulls in it? Please be more specific about your actual situation. – Remy Lebeau May 30 '22 at 07:16
  • 1
    Don't, just don't. They only sane way to do is to use pointer + size when interfacing with C, or std::span, std::string, std::array or std:vector in C++. A C string ends at the first `\0` and can't hold `\0` chars by design. – Goswin von Brederlow May 30 '22 at 08:34

1 Answers1

3

how can i calculate the size of value ... the structure of my program is in a way that i can not use array and it should be pointer.

There is no built-in function for this scenario.

The only possibility to calculate the string length is if either:

  • the string is double null-terminated, eg: Hello\0Hello\0\0

  • if you know in advance how many intermediate null characters exist in the string before the final null terminator.

In either case, you can then enumerate the string, counting the chars and skipping the intermediate nulls, until you reach the final null terminator.

If neither of those cases is true in your situation, then you are out of luck unless you have an out-of-band way to know the string's length.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • and until when the while should be continue as we dont know the size of value? and how can i specify which null parameter is a null terminator? – Lia May 30 '22 at 07:04
  • @Lia please re-read my answer again more carefully, I already covered that. – Remy Lebeau May 30 '22 at 07:09
  • @Lia as stated in the answer you need some external knowledge, either the number of nulls or the fact that the string ends with two nulls – Alan Birtles May 30 '22 at 07:09