How can I convert an integer to a string for inclusion in another string? eg, here's a try with typecasting that doesn't work:

Code:

int main () {
int x=5;
char *str=(char*)x;
printf("&#37;s", str);
}

Compiles fine but segfaults.

08-06-2008

matsp

Yes, it would crash. You are trying to read a string from locaiton 5 in memory.

To concatenate a number to a string, you need to convert the internal (binary) representation to a string, and then concatenate the string. An easy way to do that would be to use sprintf() to "print" the number into a string buffer - you could even do something like this: