I am trying to create a program to transform a integer
into string
:
#include <stdio.h>
char int_to_char(int num){
int i=0;
for(int a=num; a!=0; i++) a/=10;
char s[i+1];
for(int a=num; i!=0; i--){
s[i-1] = (a % 10) + 48;
a/=10;
}
return *s;
}
int main(void){
char a = int_to_char(123);
printf("%c\n", a);
return 0;
}
What it does is:
- Calculate the length of the number.
- create an array
s
with that length. - fill
s
with the ascii of each number.
The problem is that it returns only the first digit of the array s
, how do I make it return the entire array?
If your idea is to convert a number to a string, you need to return an array of characters... not just one character:
Now, to manage the character strings you are using a VLA (Variable Length Array):
A VLA is a fixed-size array whose size is determined by a variable, that is, its size is fixed at runtime rather than compile time.
One feature of VLAs is that they are created on the program stack, then their life cycle is strictly controlled. In other words... like any other variable, its memory will be freed when the scope of that variable is left.
So you can't use VLA in your code. Solution? Use dynamic memory:
Of course, you have to remember to end the character string with
'\0'
... we can save this point if we already leave the character array correctly initialized:While
malloc
limiting itself to allocating dynamic memorycalloc
, apart from allocating memory, it initializes all array positions to 0.The small downside of managing dynamic memory is that you have to remember to free it manually when you no longer need it:
Now, there is a more elegant way to calculate the number of digits in a number... the base 10 logarithm. It's easy to verify that:
So, just add one to the result (always working with integers to discard the decimal part) to get the number of digits in a number:
Putting it all together, we would have something like this: