Leon Benko Leon Benko - 3 months ago 15
C Question

How to reverse digits of each number in an array using pointer arithmetic

I tried to write a program in C that reverses all the numbers in an array, but it actually doesn't reverse anything, so I get unchanged numbers back. I guess I got something wrong with the pointers.

Here is my code:

#include <stdio.h>

void reverse(int *n) {
int number = *n, number2 = 0;

while (number!=0) {
number2 *= 10;
number2 += number % 10;
number /= 10;
}

*n = number2;
}

void ReverseDigits(int *p, int n) {
int i = 0;

while (i < n) {
reverse(&p);
p++;
i++;
}
}

int main() {
int array[3] = {123, 456, 789}, i = 0;

while (i < 3) {
ReverseDigits(array, 3);
i++;
}
return 0;
}

Answer

In ReverseDigits the variable p is an int pointer. When you do &p you'll get a pointer to int pointer. But your reverse function just expects an int pointer so your call of reverseis wrong. Simply do

reverse(p);  // insteand of reverse(&p)

In main you shall not call ReverseDigits in a loop as the function already loops the array (i.e. the number of elements passed). So skip the while and simply do:

int main() {
    int array[3] = {123, 456, 789};

    ReverseDigits(array, 3);

    return 0;
}