Unfortunately, none of the answers above can really work in their pure form in a situation where you need to come up with a string of alphanumeric characters. There are really strange cases that I have seen, especially in interviews and at work.
The only bad part of the code is that you need to know the bounds of the whole so that you can properly assign the string.
Although C is considered predictable, it can have strange behavior in a large system if you get lost in coding.
The solution below returns an integer representation string with a null terminating character. It does not depend on any external functions and works with negative integers !!
#include <stdio.h> #include <stdlib.h> void IntegertoString(char * string, int number) { if(number == 0) { string[0] = '0'; return; }; int divide = 0; int modResult; int length = 0; int isNegative = 0; int copyOfNumber; int offset = 0; copyOfNumber = number; if( number < 0 ) { isNegative = 1; number = 0 - number; length++; } while(copyOfNumber != 0) { length++; copyOfNumber /= 10; } for(divide = 0; divide < length; divide++) { modResult = number % 10; number = number / 10; string[length - (divide + 1)] = modResult + '0'; } if(isNegative) { string[0] = '-'; } string[length] = '\0'; } int main(void) { char string[10]; int number = -131230; IntegertoString(string, number); printf("%s\n", string); return 0; }
source share