Reputation: 2279
I'm trying to count the number of chars in a char array including the space until the end of the string.
The following compiles but doesn't return the correct value, I'm trying to use pointer arithmetic to interate through my array.
int numberOfCharsInArray(char* array) {
int numberOfChars = 0;
while (array++ != '\0') {
numberOfChars++;
}
return numberOfChars;
}
Many thanks.
Obviously I'm trying to get the equivalent of length() from cstring but using a simple char array.
Of course if my original array wasn't null terminated this could cause a very big value to return (I guess).
Upvotes: 0
Views: 37709
Reputation: 20383
static const size_t maxExpectedChars = 4 * 1024; // Max chars expected, e.g. 4K
size_t numberOfCharsInArray( char * array) {
if( !array ) { return 0; } // A non-existing string has `0` length
size_t charsSoFar = 0;
while ( *array ) {
charsSoFar += 1;
if( charsSoFar == maxExpectedChars ) { break; } // Stop runaway loop
++array;
}
return charsSoFar;
}
Upvotes: 0
Reputation: 455142
To access the char pointer by the pointer you need to dereference the pointer. Currently you are
comparing array
( an address) with
'\0'
You can fix your code like:
int numberOfCharsInArray(char* array){
int numberOfChars = 0;
while (*array++){
numberOfChars++;
}
return numberOfChars;
}
The cstring function you are imitating is strlen
not length
.
EDIT:
To know how the condition in the while works you can see this thread.
Upvotes: 7
Reputation: 101456
Perhaps I'm missing something, but why not just:
int numberOfCharsInArray(char* array) {
return strlen(array);
}
...or even:
int numberOfCharsInArray(char* array) {
return std::string(array).length();
}
Upvotes: 4
Reputation: 11227
When you write array++ != '\0'
you check if the memory address array
is '\0'. Try this instead:
int numberOfCharsInArray(char* array){
int numberOfChars = 0;
while (*array != '\0'){
numberOfChars++; array++;
}
return numberOfChars;
}
Edit: Oops, codaddict was faster and his code more elegant.
Upvotes: 2