如何查找包含零作为元素的char数组的长度

时间:2014-07-01 22:09:47

标签: c++ char

想知道如何找到char数组的长度。 例如

char buffer[20];
buffer[0] = 0x01;
buffer[1] = 0x02;
buffer[3] = 0x00;
buffer[4] = 0x04;
buffer[5] = 0x01;
buffer[6] = 0x02;
buffer[7] = 0x00;
buffer[8] = 0x04;

std::cout << "the len of array = "<< strlen(buffer) << std::endl;

o/p = the len of array = 3

预期o / p = 8

NOw问题是0可以出现在字符元素数组中的任何地方。我需要真正的len即8

3 个答案:

答案 0 :(得分:3)

C(或C ++)中的数组不会跟踪存储在其中的数据量。如果你想知道存储数据的大小(而不是数组的大小),你需要在另一个变量中跟踪它,或者使用标记存储结束的标记(例如NULL)数据

或者,由于您似乎正在使用C ++(尽管有C标记),您可以使用跟踪大小的std::vectorstd::string

答案 1 :(得分:1)

在C ++中,您可以使用std::vector<char>std::string。两者都独立于数据存储长度,因此可以在其中保留零。

请注意&#39; c&#39;样式文字字符串始终零终止,因此以下代码为您提供一个空字符串,因为NUL会提前终止字符串构造。

std:string foo("\0Hello, world!");

答案 2 :(得分:0)

如果有数组,可以使用sizeof来获取数组使用的总内存。

char buffer[20];
// 
// ...
//

size_t size = sizeof(buffer); // This gives you total memory needed to hold buffer.
size_t length = sizeof(buffer)/sizeof(char); // In this case size and length will be
                                             // same since sizeof(char) is 1.

如果您有其他类型的数组,

int buffer[20];
// 
// ...
//

size_t size = sizeof(buffer); // This gives you total memory needed to hold buffer.
size_t length = sizeof(buffer)/sizeof(int); // The length of the array.

使用sizeof来获取数组使用的内存时,需要注意一些陷阱。如果将buffer传递给函数,则会失去计算数组长度的能力。

void foo(char* buffer)
{
   size_t size = sizeof(buffer); // This gives you the size of the pointer
                                 // not the size of the array.
}

void bar()
{
   char buffer[20];

   // sizeof(buffer) is 20 here. But not in foo.

   foo(buffer);
}

如果您需要始终能够计算数组的长度,std::vector<char>std::string是更好的选择。

void foo(std::vector<char>& buffer)
{
   size_t size = buffer.size() // size is 20 after call from bar.
}

void bar()
{
   std::vector<char> buffer(20);
   size_t size = buffer.size() // size is 20.

   foo(buffer);
}