I need to store the following strings in 3 char * variables in C:
[foo]
[foo]:[bar]
[foo]:[bar]:[tat]
Each individual string such as “foo” is received at one point of time via a char* pointer, the corresponding output string is produced immediately before receiving the second string, and the total number of individual strings is known at all times.
There can be an arbitrary number of strings.
I wrote the following code to print the strings:
for(i=0;i<num;i++)
{
for(j=0;j<=i;j++)
{
printf("[%s]",str[j]);
if(j!=i)
{
printf(":");
}
else
{
printf("\n");
}
}
}
But I am unable to figure out a way of storing the desired output strings in variables, other than writing a messy case-by-case function using strcat() & some additional self-defined functions.
Is there a way to do this, that looks as clean as simply printing the strings?
This is a memory-management-and-string-handling-in-C-are-tedious problem. If I’m right in thinking that for n input strings, you want n output strings, each longer than the last, I’d do this:
Or something like that. Obviously there’s a good opportunity to write more than one function here, to separate the generation of these strings from the storing of them in arrays. There’s also the usual argument how we can do better in the risk-of-buffer-overflow stakes than
sprintf+ mental arithmetic.Edit: stole the use of
sprintffrom Oskar.Another edit: example with
asprintf, which is available on GNU and BSD. This has the tedious freeing code included, the success path is actually quite good. Returns a newly-allocated array on success, 0 on error. The caller is assumed to knownumand therefore know how long the array will be: if that’s no use then the array could be null-terminated.