pembed2003 wrote:
Hi all,
As an exercise, I am trying to come up with a function to count the
length of a char* string using recursion. I came up with this:
int count_length(char* s){
if(s == 0)
return 0;
else{
s++;
return 1 + count_length(s);
}
}
but it doesn't work. There is a core dump / illegal operation. I tried
yes, because you never stop counting.
to fix it by:
int count_length(char* s){
if(s == 0 || !*s)
return 0;
else{
s++;
return 1 + count_length(s);
}
}
This seems to fix the problem and return the correct length. I tested
it with:
yup. the test you have about now first checks to make sure that s is not
a null pointer, then checks to make sure that _what s points to_ is not
0, which denotes the end of the string.
for a clearer example, consider this:
if (s == 0) {
//s is null
}
if (*s == char(0)) { // note the cast for clarity
//s points to a null character - the end of a string
}
if you want my opinion, i'd recommend that you don't return 0 as the
length of a null pointer "string". null pointers are problematic (and
have obviously confused you slightly).
perhaps better would be:
int count_length(char* s){
assert(s != 0);
if (*s == '\0')
return 0;
else{
s++;
return 1 + count_length(s);
}
}
or if you do not want to assert, then return -1 or something. that is,
of course, unless you want to allow for null pointer "strings".
remember:
char* str = 0; // null pointer
is not the same as:
char* str = ""; // zero-length string
mark