C将字符串解析成一系列字符串
在定义一系列字符串的同时,我通常会声明它类似于以下内容:
char *arr[5] =
{
"example0",
"example1",
"example2",
"example3",
"example4"
};
我遇到问题的地方是我不知道如何将变量传递到arr
的元素之一中。
例如,
char str[6] = "1.0.0.1";
char *arr[6] =
{
"example0",
"example1",
"example2",
"example3 %s", str,
"example4"
};
当然,这无效,这只是我遇到的问题的基本说明。
我也知道我以后可以使用strncat()
或什至snprintf()
,但是,为避免使用这些记忆的痛苦,我只想知道是否解析变量在声明时,可以进入阵列的一个字符串。
While defining an array of strings, I usually declare it similar to the following:
char *arr[5] =
{
"example0",
"example1",
"example2",
"example3",
"example4"
};
Where I'm having a problem is I don't know how to pass a variable into one of the elements of arr
.
For instance,
char str[6] = "1.0.0.1";
char *arr[6] =
{
"example0",
"example1",
"example2",
"example3 %s", str,
"example4"
};
Of course, this doesn't work, it's just a basic illustration of what I'm having trouble with.
I also know I can later use strncat()
or even snprintf()
but, to avoid the pain of handling memory with those, I just want to know if parsing a variable into one of the strings of the array is possible at declaration.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在编译时,可以如下:
OP对运行时形成的东西感兴趣。它使用变量长度阵列(vla)。
或者
,可以通过分配来完成 string 的空间。
At compile time, could concatenate as below:
Perhaps OP is interested in something formed during run-time. It uses a variable length array (VLA).
Output
Alternatively the space for the string could have been done via an allocation.