Reputation: 2214
wondering how would I find the length of char array . for example
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
expected o/p = 8
NOw issue is zeros can occur anywhere in the array of character elements.and I need true len i.e 8
Upvotes: 1
Views: 935
Reputation: 206647
When you have an array, you can use sizeof
to get the total memory used by the array.
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.
If you have an array of other types,
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.
There are pitfalls to be aware of using sizeof
to get the memory used by an array. If you pass buffer
to a function, you lose the ability to compute the length of the array.
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);
}
If you need to be able to compute the length of the array at all times, std::vector<char>
and std::string
are better choices.
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);
}
Upvotes: 0
Reputation: 68053
In C++ you would use a std::vector<char>
or a std::string
. Both store the length independently of the data so can hold zeros in them.
Beware that 'c' style literal strings are always zero terminated, so the following code gives you an empty string because the NUL terminates the string construction early.
std:string foo("\0Hello, world!");
Upvotes: 1
Reputation: 126328
Arrays in C (or C++) don't keep track of how much data has been stored in them. If you want to know the size of the stored data (as opposed to the size of the array), you'll need to track that yourself in another variable, or use a sentinel (such as NULL) that marks the end of the stored data.
Alternately, since you appear to be using C++ (despite the C tag), you can use a std::vector
or std::string
which tracks the size for you.
Upvotes: 3