sizeof的一个空终止为const

sizeof的一个空终止为const

本文介绍了sizeof的一个空终止为const char *的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

const char* a;

我如何确保字符串'一'是空终止?当a =ABCD和我的sizeof(一),我得到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 ?

推荐答案

如果你都交给这可能会或可能不会有它的空值终止的数据的字符数组,实在是没有检查的好办法。你能做的最好是寻找一个空字符到一个certian指定的长度(不能无限期地!)。但是0是不完全数据的异常字节的内存uninitialzed区域找到。

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(字符*),而不是数组的长度。

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的一个空终止为const char *的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 16:34