'C parsing a string into an array of strings
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.
Solution 1:[1]
... if parsing a variable into one of the strings of the array is possible at declaration.
At compile time, could concatenate as below:
#define STR "1.0.0.1"
char str[] = STR;
char *arr[6] = {
"example0",
"example1",
"example2",
"example3" " " STR, // Forms "example3 1.0.0.1"
"example4"
};
Perhaps OP is interested in something formed during run-time. It uses a variable length array (VLA).
void foobar(const char *str) {
int n = snprintf(NULL, 0, "example3 %s", str);
char a[n]; // VLA.
snprintf(a, sizeof a, "example3 %s", str);
char *arr[6] = {
"example0",
"example1",
"example2",
a,
"example4"
};
printf("<%s>\n", arr[3]);
}
int main(void) {
foobar("1.0.0.1");
}
Output
<example3 1.0.0.>
Alternatively the space for the string could have been done via an allocation.
char *a = malloc(n + 1u);
sprintf(a, "example3 %s", str);
....
free(a);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
