#include <stdio.h>
#include <stdlib.h>
char *ft_strcpy(char *dst, const char *src) {
int i = -1;
do {
i++;
dst[i] = src[i];
} while (src[i]);
return dst;
}
int ft_strlen(const char *src) {
int i = 0;
while (src[i]) i++;
return i;
}
char *ft_concat_params(int argc, char **argv) {
// Cache com os tamanhos das strings.
int *cache
= (int *) malloc(argc
* sizeof(int));
// Conta o tamanho das strings.
int count = 1; // 1 = espaço do terminador nulo.
for (int i = 0; i < argc; i++) {
cache[i] = ft_strlen(argv[i]);
count += cache[i];
}
// Cria a nova string que será retornada.
char *newString
= (char *) malloc(count
);
// Copia as strings para o newString.
// Usa aux para percorrer o espaço de memória de newString.
char *aux = newString;
for (int i = 0; i < argc; i++) {
ft_strcpy(aux, argv[i]);
aux = &(aux[cache[i]]);
}
// Adiciona o terminador nulo.
aux[0] = 0;
// Não precisamos mais da cache.
// Terminamos.
return newString;
}
int main(void) {
const char *strings1[] = {"banana", "pera", "uva"};
char *a = ft_concat_params(3, strings1);
printf("[%s] - %d\n", a
, ft_strlen
(a
));
const char *strings2[] = {"", "teste", "", "mais", "", "perigoso", ""};
char *b = ft_concat_params(7, strings2);
printf("[%s] - %d\n", b
, ft_strlen
(b
));
const char *strings3[] = {"", "", ""};
char *c = ft_concat_params(3, strings3);
printf("[%s] - %d\n", c
, ft_strlen
(c
));
const char *strings4[] = {};
char *d = ft_concat_params(0, strings4);
printf("[%s] - %d\n", d
, ft_strlen
(d
));
return 0;
}
I2luY2x1ZGUgPHN0ZGlvLmg+CiNpbmNsdWRlIDxzdGRsaWIuaD4KCmNoYXIgKmZ0X3N0cmNweShjaGFyICpkc3QsIGNvbnN0IGNoYXIgKnNyYykgewogICAgaW50IGkgPSAtMTsKICAgIGRvIHsKICAgICAgICBpKys7CiAgICAgICAgZHN0W2ldID0gc3JjW2ldOwogICAgfSB3aGlsZSAoc3JjW2ldKTsKICAgIHJldHVybiBkc3Q7Cn0KCmludCBmdF9zdHJsZW4oY29uc3QgY2hhciAqc3JjKSB7Ci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