Reputation: 33
I have a char array and I want to find out the number of contents in it. For example, my array is:
char myArray[10];
And after input it's content is:
ABC
Now I want to store in a variable 'size', the size of the area related to content. So, in this case:
size = 3
How do I find that?
Upvotes: 0
Views: 53
Reputation: 146
defining array as char myArray[10];
will not always initialize it's content to zeros, so depending on how you fill it with ABC you either can or cannot find the corect lenght. In worst case regular strlen() will always report numbers >10, or even result in read access vialation. I try initialize it like char myArray[10] = {};
first
Upvotes: 0
Reputation: 810
Try this:
int len = strlen(myArray).
strlen is a part of stdlib.h library. Don't forget to declare it in your program.
Upvotes: 0
Reputation: 5980
A naive way of doing this would be to look for the null-terminating character \0
, this is already implemented for you in the C-function strlen
, so there are two ways of doing this:
int StringLength( const char* str, int maxLength )
{
for( int i = 0; i < maxLength; ++i )
{
if( str[i] == '\0' )
return i;
}
return -1;
}
Or you could just call strlen
as follows:
int iLength = strlen( myArray );
However, as you have tagged this c++, the best way to do this would be to not deal with C-style character arrays and instead use the extremely useful std::string
class.
Upvotes: 3