查找字符数组的长度 [英] Finding length of char array
问题描述
我有一些代码如下:
int i=0;
char a[7]={0x00,0xdc,0x01,0x04};
int len=0;
len = sizeof(a);
printf("The Length is : %d", len);
这里我想在c中找到数组a
的长度?这怎么办?
Here I want to find the length of the array a
in c?
How can this be done?
推荐答案
按照约定,C 字符串是以空字符结尾的".这意味着末尾有一个额外的字节,其值为 0 (0x00
).任何对字符串执行某些操作的函数(如 printf
)都会在它找到 null 时认为字符串结束.这也意味着如果你的字符串不是空终止的,它会一直运行直到找到一个空字符,这会产生一些有趣的结果!
By convention C strings are 'null-terminated'. That means that there's an extra byte at the end with the value of zero (0x00
). Any function that does something with a string (like printf
) will consider a string to end when it finds null. This also means that if your string is not null terminated, it will keep going until it finds a null character, which can produce some interesting results!
由于数组中的第一项是 0x00,因此它将被视为长度为零(无字符).
As the first item in your array is 0x00, it will be considered to be length zero (no characters).
如果您将字符串定义为:
If you defined your string to be:
char a[7]={0xdc,0x01,0x04,0x00};
例如空终止
然后就可以使用strlen
来测量存储在数组.
then you can use strlen
to measure the length of the string stored in the array.
sizeof
测量类型的大小.这不是你想要的.还要记住,数组中的字符串可能比数组的大小还短.
sizeof
measures the size of a type. It is not what you want. Also remember that the string in an array may be shorter than the size of the array.
这篇关于查找字符数组的长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!