Reputation: 267
I am current writing a code which returns the position of a certain digit of a user input. I am currently facing a problem where my pointer is not working, which I believe is due to the recursion function. Any advice would be appreciated!
#include <stdio.h>
void rDigitPos2(int num, int digit, int *pos);
int main()
{
int number;
int digit, result = 0;
printf("Enter a number: ");
scanf("%d", &number);
printf("Enter the digit: ");
scanf("%d", &digit);
rDigitPos2(number, digit, &result);
printf("rDigitPos2(): %d", result);
return 0;
}
void rDigitPos2(int num, int digit, int *pos) {
static int count = 0;
if (num % 10 != digit) {
count++; //increment of position
rDigitPos2(num/10, digit, &pos);
*pos = count;//returns the position of the digit
}
Upvotes: 4
Views: 1415
Reputation: 5741
Effectively return the 1 base position your rDigitPos2
would be like
void rDigitPos2(int num, int digit, int *pos)
{
static int count = 0;
if (num % 10 != digit)
{
count++; //increment of position
rDigitPos2(num/10, digit, pos); //Not &pos
}
else
{
*pos = count; //Current position from the last
while(num!=0)
{
num = num/10;
count++;
}
*pos = count-*pos; //Original position form beginning
}
}
As your first part of recursion find the position from the last, it would be need to find the length of the number then length-position from last
would be your answer.
Upvotes: 0
Reputation: 31
rDigitPos2(num/10, digit, &pos);
to
rDigitPos2(num/10, digit, pos);
Since the paramater (pos) is already passed to the function in the first call, passing the (&pos) in the recursive call will lead to passing of the address of address of (pos).
Some improvements
-Happy coding :)
Upvotes: 1
Reputation: 1254
GCC compiler gives a significant warning, replace &pos
with pos
ss.c:20:31: warning: incompatible pointer types passing 'int **' to parameter of type 'int *'; remove & [-Wincompatible-pointer-types]
rDigitPos2(num/10, digit, &pos);
^~~~
Humble request, Please do not ignore warnings :)
Upvotes: 0
Reputation: 3767
change
rDigitPos2(num/10, digit, &pos);
to
rDigitPos2(num/10, digit, pos);
along with minor details
Upvotes: 0