Question:
how can i concatenate an int with a char * in C?
themadman
2006-09-28 11:54:57 UTC
i know how to convert from an int to a "string." but then, i don't know how to concatenate that "string" to a char *. this is the code i have so far

char * result = "abcdefg";
char dummy[10];
int x = 12;
sprintf(dummy, "%d", x);

i have tried to print "dummy" and it worked. but when i used the function "strcat(result, dummy)" and tried to print "result", it gave me segmentation fault. please help me
Four answers:
2006-09-28 16:26:35 UTC
The previous responders have the right idea but the wrong target!



Instead, try

char result[32] = "abcdefg";

char dummy[10];

int x=12;

sprintf(dummy, "%d", x);

strcat(result, dummy);



What you were doing was not allocating space for result! Your compiler just gave it enough space for its initializing string, and not enough for concatenating anything onto it.
barrabe
2006-09-28 15:00:19 UTC
You need to make sure your output string is big enough to hold the concatenated string (length of result string + length of int converted to string). dummy only has space for 9 characters + the "null character" (\0) that's why you get a segfault.



If you are using sprintf() to convert your int, you can do the concatenation at the same time:



char dummy[1024]; /* or something big enough */

sprintf(dummy, "%s%d", result, x);

printf("%s\n", dummy); /* should output abcdefg12 */
Syntax-Error
2006-09-28 12:05:16 UTC
define a larger array for dummy and try again. It seems that it is very small.



abcdefg is 7 chars and plus the NULL char ( '\0' ) that makes 8, you have 2 left!!



make it



char dummy[100] or something.



also read the below link about strcat..



Peace
lance
2006-09-28 12:19:24 UTC
First you have to put an index into the array to view its content for example:



for(int indx = 0; indx < 10; indx++)

{

sprintf("%c",dummy[indx],"%d",x);

}



indx is incremented the caracter "%c" display the caracter content of the array and you dont need to convert to int.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...