Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
664 views
in Technique[技术] by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...