-
recursive function
I am getting a Seg Fault; can anyone explain the problem??
I believe this simple program is to find the # of instances a letter s occurs in the string literal "system" (which is obviously 2 times).
I am reviewing some programs for my final and I am obviously missing something quite simple but darned if I see it right now.
Code:
#include <stdio.h>
int Example2(char ch, char *str)
{
int result, i;
if (str[0] == '\0')
result = 0;
else if
(ch == str[0])
result = 1+Example2(ch,&str[i]);
else
result = Example2(ch,&str[i]);
return result;
}
main()
{
char a = 's';
char message[20] = "system";
printf("returned from Example2: %d\n",
Example2(a,message));
return 0;
}
-
You have a variable i that is never initialized and its value never changed. Try initializing i to 0 and increment its value in every recursive call.
Code:
#include <stdio.h>
int Example2(char ch, char *str)
{
int result;
int i = 0; // initialize to 0
if (str[i] == '\0')
result = 0;
else if (ch == str[i])
result = 1+Example2(ch,&(str[++i]));
else
result = Example2(ch,&(str[++i]));
return result;
}
main()
{
char a = 's';
char message[20] = "system";
printf("returned from Example2: %d\n",
Example2(a,message));
return 0;
}
David
-
For the sake of redundancy....
The lines that are actually recursive in your program access undefined memory addresses. Clearly, your Example2 function is meant to perform it's recursive step on the string that would start at the next letter...
Code:
int Example2(char ch, char *str)
{
int result;
if (str[0] == '\0')
result = 0;
else if (ch == str[0])
result = 1+Example2(ch, str + 1));
else
result = Example2(ch, str + 1));
return result;
}
This is the effectively same code as Strider's of course, but I think it's important to note that all your recursive call is really supposed to do is advance the pointer by one (the terminating condition being when the pointer is at '/0').