如何计算指针指向的字符串大小

发布于 2025-02-02 23:32:36 字数 217 浏览 3 评论 0原文

假设我有一个类似的炭指针:

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

如何计算值的大小,因为strlen仅计算字符串的大小,直到“/0”,所以我不能使用strlen < /code>,并且sizeof还返回指针本身的长度,因此有什么方法可以计算值的长度?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

情痴 2025-02-09 23:32:36

我如何计算价值的大小...程序的结构是我无法使用数组的方式,应该是指针。

对于这种情况,没有内置功能。

计算字符串长度的唯一可能性是:

  • 字符串为 double null-terminited,例如:hello \ 0hello \ 0 \ 0 \ 0

  • 如果您提前知道字符串中的字符串中存在多少个中间null字符最终的零终端。

无论哪种情况,您都可以枚举字符串,计算字符并跳过中间零,直到到达最终的空终止器。

如果在您的情况下,这些情况都不是真实的,那么除非您有不知道字符串的长度的方式,否则您将不幸。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文