# Pointers & Integer Arithmetic Question

trying to do a simple exercise on pointers because my recover isn't working (and I think it has to do with pointers). Wanted to write a program that reverses digits using pointers.

Unfortunately I get a segmentation fault (below). I'm not sure why dividing the number gets down to one and then loops forever never getting to 0.

Does it have to do with the pointer? The math? The data type? Normally if you divide 2 / 10 you get 0?

Any help would be appreciated!

``````#include <stdio.h>
#include <cs50.h>

int mod (int *a, int num); // dereferences the number, divides it by 10 and stores the value into an array

int main (void)
{
int num, digit; // 2 integers
int* a = &num; // pointer to the address of number

int right_num[100]; // array for digits; originally initialized to 0 but got a segfault
digit = 0; // counter

// get the number

printf("Welcome to Reverse. \n");
printf("What integer would you like to reverse?");
scanf("%i",&num);

// this is now an infinite loop and I'm not sure why

while (num > 0) // should evaluate to 0 when mod divides a number less than 10 by 10 but it doesn't.
{
printf("the value of num and pointer are %i and %i\n", num, *a);
right_num[digit] = mod(a, num); // adding the right most digit to the array by calling mod
++digit;
}

// print out the reverse of the number

printf("The reverse of your number is: ");

for (int i = 0; i < digit; i++)
{
printf("%i",right_num[i]);
}

printf("\n");

return 0;

}

// takes a pointer and the number, figures out if there's any digits left by dividing by 10; stores the right most digit in value and returns it to the array

int mod(int *a, int num)

{
if (num / 10 > 0)
{
int value = num % 10;
printf("value is %i\n", value);
*a = *a / 10;
return value;
}
else
{
return 0;
}
}
``````

## 1 Answer

you loop runs infinitely because `num` never reduces again when it is less than 9. but you else has problem.

``````int mod(int *a, int num)
{
if (num/10  > 10)
{
int value = num % 10;
printf("value is %i\n", value);
*a = *a / 10;
return value;
}
else
{
int value = num;
// you can set it to zero now because it was the last digit of your number
*a = 0;
return value;
}
}
``````