P
pembed2003
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
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:
count_length(0);
count_length("12345");
My question is: Why is the first version not work? I though the "if(s
== 0)" check will catch the null pointer, no? Can someone explain to
me? Thanks!
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
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:
count_length(0);
count_length("12345");
My question is: Why is the first version not work? I though the "if(s
== 0)" check will catch the null pointer, no? Can someone explain to
me? Thanks!