sizeof 用于以 null 结尾的 const char* [英] sizeof for a null terminated const char*

查看:20
本文介绍了sizeof 用于以 null 结尾的 const char*的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

const char* a;

如何确保字符串 'a' 以空值结尾?当 a = "abcd" 并且我执行 sizeof(a) 时,我得到 4.这是否意味着它不是以空值结尾的?如果是的话,我会得到 5 个?

how do I make sure that string 'a' is null terminated? when a = "abcd" and I do sizeof(a), I get 4. Does that mean its not null-terminated? if it were, I would have gotten 5 ?

推荐答案

如果你收到一个 char 数组,其中可能有也可能没有以 null 结尾的数据,那么确实没有一个好的方法来检查.您可以做的最好的事情是搜索一个空字符,直到指定长度(不是无限期!).但 0 并不是在未初始化的内存区域中找到的不寻常的数据字节.

If you are handed a char array which may or may not have null-terminated data in it, there really isn't a good way to check. The best you can do is search for a null character up to a certian specified length (not indefinitely!). But 0 isn't exactly an unusual byte of data to find in an uninitialzed area of memory.

这是许多人不喜欢的关于 C 的事实上的字符串标准的许多事情之一.查找客户端提供给您的字符串的长度充其量是 O(n) 搜索操作,最坏的情况是分段错误.

This is one of the many things about C's defacto string standard that many people dislike. Finding the length of a string a client hands you is an O(n) search operation at best, and a segmentation fault at worst.

当然,另一个问题是数组和指针是可以互换的.这意味着 array_name + 2&(array_name[2]) 相同,而 sizeof(a)sizeof(char*),而不是数组的长度.

Another issue of course is that arrays and pointers are interchangable. That means array_name + 2 is the same as &(array_name[2]), and sizeof(a) is sizeof(char*), not the length of the array.

这篇关于sizeof 用于以 null 结尾的 const char*的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆