I initially wrote a perfectly working C code for converting a positive integer (say 12345) to a string (i.e. "12345") and print it. The logic is simple: extracting the digits of the integer one-by-one by taking modulo 10 and reducing the integer by a factor of 10 each time (this occurs in the itos()
function). The final string needs to hold the extracted digits in reverse order so as to match the original integer (cf. reverse()
function).
#include <stdio.h>
#include <string.h>
char *reverse (char *s);
char *itos (int n);
int
main ()
{
int n = 12345;
char *s = itos (n);
printf ("%s", s);
return 1;
}
char *
itos (int n)
{
int d = 0;
char s[100];
int i = 0;
do
{
d = n % 10;
s[i] = (d + '0');
n = n / 10;
i++;
} while (n != 0);
s[i] = '\0';
return reverse(s);
}
char *
reverse (char *s)
{
int i = 0;
int j = strlen (s) - 1;
char temp;
while (i < j)
{
temp = s[i];
s[i] = s[j];
s[j] = temp;
i++;
j--;
}
return s;
}
You may compile it here. This works perfectly fine, but something strange happens if I return s
instead of reverse(s)
from the char* itos()
function. That is:
#include <stdio.h>
#include <string.h>
char *itos (int n);
int
main ()
{
int n = 12345;
char *s = itos (n);
printf ("%s", s);
return 1;
}
char *
itos (int n)
{
int d = 0;
char s[100];
int i = 0;
do
{
d = n % 10;
s[i] = (d + '0');
n = n / 10;
i++;
} while (n != 0);
s[i] = '\0';
return s;
}
I'd have expected it to simply print the string "54321" instead of "12345". However, in the output screen, I simply get a (null)
. There might be a logical error in the char* itos()
function, as in I might have done some illegal pointer operation, but I can't really locate the source of error.
I did try debugging by inserting print statements in several parts of the code. What I noticed is if I print the string s
within the itos()
function just before the return
statement then it works fine and prints the string "54321". However, the print statement in the main()
function still outputs a (null)
, which probably implies that there is some mismanagement of memory when the itos()
function returns a character pointer to the main()
function. Could someone please clarify?