Okay. Let's start by talking about what a string is in the C language. Fundamentally, it's a character pointer char *
to a location in memory that stores a null terminated series of characters.
An example of this would be:
char *str = malloc(3);
str[0] = 'h';
str[1] = 'i';
str[2] = '\0';
str
now contains the String "hi"
.
What does a type cast do?
The type casting that you are doing takes the integer 9009, and converts it to a char *
. Then, since you use that pointer as a string, means that you are telling the computer that at address 9009, there is a null terminated series of bytes.
That's probably not true though, and unless you are on specialized hardware, is certainly not what you want.
How do you convert an integer to a string
We have a fairly easy mechanism to convert printf-able data to strings via snprintf()
.
First we need to allocate memory for the resultant string. This is a common difference in C from other languages. In C, you are very aware of the memory requirements of your data.
char str[100];
int size_used = snprintf(str, 100, "%d", 9009);
assert(size_used < 100);
Now, if size_used >= 100
, then we have a problem. We overflowed our memory area. snprintf()
will write as many characters as it can, but not the null terminating zero in that case.