问题描述
我有一些code如下:
I have some code as follows
int i=0;
char a[7]={0x00,0xdc,0x01,0x04};
int len=0;
len = sizeof(a);
printf("The Length is : %d", len);
在这里,我想找到在C数组的长度?
我该怎么办呢?
Here I want to find the length of the array a in c?How can I do it?
推荐答案
按照惯例C字符串是空值终止。这意味着,有一个在与零值结束一个额外的字节( 0×00
)。那做了一个字符串(如的printf
)的任何函数会考虑一个字符串结束时,发现空。这也意味着,如果你的字符串不是空终止,它会继续下去,直到找到一个空字符,它可以产生一些有趣的结果!
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};
例如。空值终止
那么你可以使用来衡量长度存储在数组中的字符串
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.
这篇关于查找字符数组长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!