S
Silas Silva
Hello all!
I'm learning C and I started to get into malloc() and va_* functions
of stdarg.h (va_list, va_arg, va_start, etc). So I wrote the following
program that has a funcion that concatenates strings:
/********** START ***********/
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char *concat(int, ...);
int
main(void) {
printf("%s\n", concat(3, "foo ", "bar ", "mubble"));
exit(0);
}
char *
concat(int argc, ...) {
va_list list;
int i;
int size;
char *arg; /* Arguments of the list */
char *stringstart; /* Start address of the string */
char *string; /* String that will receive the values */
va_start(list, argc);
size = 0;
for(i = 0; i < argc; i++) {
arg = va_arg(list, char *);
size += strlen(arg);
}
va_end(list);
va_start(list, argc);
stringstart = string = malloc(size * sizeof(*string));
for(i = 0; i < argc; i++) {
arg = va_arg(list, char *);
strcpy(string, arg);
string += strlen(arg);
}
va_end(list);
return stringstart;
}
/********** END ***********/
My questions are:
1) I suppose it is not possible to get the number of variable
arguments that are going to the passed to the function, so I use an
argc argument. Am I right?
2) To alloc the right size, I scan all the arguments, calculates
theirs size (sizeof) and then I pass the value to the malloc()
function. Is there a smallest way to do that?
Thank you very much!
I'm learning C and I started to get into malloc() and va_* functions
of stdarg.h (va_list, va_arg, va_start, etc). So I wrote the following
program that has a funcion that concatenates strings:
/********** START ***********/
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char *concat(int, ...);
int
main(void) {
printf("%s\n", concat(3, "foo ", "bar ", "mubble"));
exit(0);
}
char *
concat(int argc, ...) {
va_list list;
int i;
int size;
char *arg; /* Arguments of the list */
char *stringstart; /* Start address of the string */
char *string; /* String that will receive the values */
va_start(list, argc);
size = 0;
for(i = 0; i < argc; i++) {
arg = va_arg(list, char *);
size += strlen(arg);
}
va_end(list);
va_start(list, argc);
stringstart = string = malloc(size * sizeof(*string));
for(i = 0; i < argc; i++) {
arg = va_arg(list, char *);
strcpy(string, arg);
string += strlen(arg);
}
va_end(list);
return stringstart;
}
/********** END ***********/
My questions are:
1) I suppose it is not possible to get the number of variable
arguments that are going to the passed to the function, so I use an
argc argument. Am I right?
2) To alloc the right size, I scan all the arguments, calculates
theirs size (sizeof) and then I pass the value to the malloc()
function. Is there a smallest way to do that?
Thank you very much!