Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
668 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...