简体   繁体   中英

char array initialize with string and int variable (c)

i would like to initialize a char array like this:

char msg[] = "something 12";

This works so far, but to hold my function more flexibel i would like to use a integer varible instead of the fixed "12".

So i would like to use something like:

int value = 12;
char msg[] = ("something %d", value);

But this seems not to work. Is there a smart way use a flexible initialization?

Thanks for your help.

You can use snprintf() .

int value = 12;
const char* format = "something %d";
int len = snprintf(NULL, 0, format, value);
char msg[len + 1]; /* Variable-Length Array (C99) */
snprintf(msg, len + 1, format, value);

You can use sprintf to make up your string:

char result[100];
int value = 12;

sprintf(result, "Something %d", value);

printf("%s\n", result);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM