Building a string from a variable number of arguments

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>


int main(int argc, char * argv[])
{
    char *arr[] = { "ab", "cd", "ef" };
    char **ptr, **p, *str;
    int num = 3;
    int size = 0;

    ptr = calloc(num, 4);
    p = ptr;

    for (; num > 0; num--)
            size += strlen(*(p++) = arr[num - 1]);

    str = calloc(1, ++size);
    sprintf(str, "%s%s%s", ptr[0], ptr[1], ptr[2]);

    printf("%s\n", str);

    return 0;
}

conclusion: "efcdab"as expected.

now all this is fine and suitable if the count to argument is sprintfpredefined and known. However, what I'm trying to achieve is an elegant way to build a string if the count argument is a variable ( ptr[any]).

first problem: the second argument to pass to sprintfis const char *format.
second: the third argument is the actual number of arguments passed to build the string based on the provided format.

how can i achieve any of the following:

sprintf(str, "...", ...)

, , 4 ( ) char , ( , , 3). , ( ) "%s%s%s%s", ptr[0], ptr[1], ptr[2], ptr[3].

"" , sprintf ( vsprintf), ? , (** ptr) .. ? , , sprintf , ... - format.

/?

+5
4

karlphillip strcat . , - strncat (, C, , strlcat, , , , strncat).

, sprintf(str, "%s%s%s", ptr[0], ptr[1], ptr[2]); - :

int i;

for (i = 0; i < any; i++)
    strncat(str, arr[i], size - strlen(str) - 1);

( strlcat(str, arr[i], size);; strlcat , , , , C .)

+1

C .

++ std::string, .

0

: const char * , . - , .

: pass va_list. ? varargs:

char *assemble_strings(int count, ...)
{
    va_list data_list;
    va_list len_list;
    int size;
    char *arg;
    char *formatstr;
    char *str;
    int i;

    va_start(len_list, count);
    for (i = 0, size = 0; i < count; i++)
    {
        arg = va_arg(len_list, char *);
        size += strlen(arg);
    }
    va_end(len_list);

    formatstr = malloc(2*count + 1);
    formatstr[2*count] = 0;
    for (i = 0; i < count; i++)
    {
        formatstr[2*i] = '%';
        formatstr[2*i+1] = 's';
    }
    str = malloc(size + 1);

    va_start(data_list, count);
    vsprintf(str, formatstr, data_list);
    va_end(data_list);

    free(formatstr);

    return(str);
}

- varargs, vsprintf, varargs - C .

0

, str, :

for(i=0, p=str; i < num; i++)
    p += sprintf(p, "%s", ptr[i]);

for(i=0, p=str; i < num; i++)
    p += strlen(strcpy(p, ptr[i]));

, sprintf.

0
source

All Articles