persiaprince persiaprince - 1 year ago 75
C Question

How to Concatenate a Variable and Literal in Char Pointer

I have a function that takes a char pointer as an arguments. I want to manually create the char pointer for the arguments. So, I have something like:

int a = 50;
char* command_args;
command_args = "0 0 0 %d", a; //this is the main area where I neeed help. To clarify
//I'm trying to have my character array be set to "0 0 0 a" where
//a is the variable holding an integer value
a += 5;
command_args = " "; //I guess this would reset the char pointer?

I can't actually mess with the function itself so I need to do this with a char pointer.

Answer Source

You want to use sprintf() to print a variable into a string. It works like printf() but the first argument is a pointer to some allocated memory (either static on the stack or via malloc).

char command_args[STATIC_BUFFER_SIZE];
sprintf(command_args, "0 0 0 %d", a);

You should size your buffer to hold at least the largest possible string representation of whatever datatype a is. Don't forget to account for the null terminator.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download