VallyMan
VallyMan

Reputation: 135

C - Reversing an int to an array

I'm trying to reverse the digits of an integer. To do this I am:

  1. Taking the integer.
  2. Putting it into a string.
  3. Putting the string into another string in reverse.
  4. Converting the reversed string to a proper integer.

I've sort of gotten to step 3, and while it does reverse the string properly, it leaves me with a lot of odd data. The Results The top part is just the array lengths to compare. What is happening for this odd data?

int ReverseNumber(int Num) {
//Variables
int i = 0;
int j = 0;
char Number[50];
char ReversedNumber[50];
sprintf(Number,"%d", Num);

//Finding Length Of Array
do{ 
    i++;
}while(Number[i] > 10);
//i - 1(Due to Array Length)
i--;

//Reverseing
do {
    printf("%d | %d \n",j,i);
    ReversedNumber[j] = Number[i];
    printf("%c\n", ReversedNumber[j]);
    getch();
    i--;
    j++;
} while (i != -1);

int NumberLength = (strlen(Number) - 1);
//Printing
printf("%s\n", Number);
printf("%s\n", ReversedNumber);
}

Upvotes: 0

Views: 89

Answers (1)

medalib
medalib

Reputation: 937

You have to add \0 to the end of ReversedNumber after the reversing do {...} while (...) terminates:

//Reverseing
do {
...
} while (...);
ReversedNumber[j] = '\0';

Upvotes: 2

Related Questions