为什么是一个字符串的字节大小比长度更久? [英] Why is a string's byte size longer than the length?

查看:150
本文介绍了为什么是一个字符串的字节大小比长度更久?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么说的sizeof(条例) 5 ,但的sizeof(字符) 1

不应该使的sizeof(条例) 4 因为字符串的长度为4字符( 4×1 )?

Shouldn't that make sizeof("Bill") be 4 since the length of the string is 4 chars (4 x 1)?

我认为它可能有一些做与条例是一个字符数组,但为什么不增加字节大小?

I believe it may have something to do with "Bill" being an array of characters, but why does that increase the byte size?

推荐答案

C字符串是空终止。有在该字符串的末尾零的字节。假设ASCII,条例看起来像这样在内存中:

C strings are null terminated. There is a zero byte at the end of that string. Assuming ASCII, "Bill" looks like this in memory:

'B'  'i'  'l'  'l'  '\0'
0x42 0x69 0x6c 0x6c 0x00

从C标准,第 6.4.5字符串字面,第7段:

在翻译阶段7,零值字节或code追加到从字符串字面的结果或文字每个多字节字符序列。

In translation phase 7, a byte or code of value zero is appended to each multibyte character sequence that results from a string literal or literals.

如果你想获得 4 的答案长度,你应该使用的strlen(条例),而不是的sizeof

If you want to get an answer of 4 for the length, you should use strlen("Bill"), rather than sizeof.

如果你真的不想空终止,这也是有可能的,虽然可能是不明智的。这样的定义:

If you really don't want the null-terminator, that's possible too, though probably ill-advised. This definition:

char bill[4] = "Bill";

将产生一个4字节数组含法案只是字符'B'LL,没有空终止子。

will yield a 4-byte array bill containing just the characters 'B', 'i', 'l', and 'l', with no null-terminator.

这篇关于为什么是一个字符串的字节大小比长度更久?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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