fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. int ft_strlen(const char *src) {
  5. int i = 0;
  6. while (src[i]) i++;
  7. return i;
  8. }
  9.  
  10. char *ft_concat_params(int argc, char **argv) {
  11.  
  12. // Conta o tamanho das strings.
  13. int count = 1; // 1 = espaço do terminador nulo.
  14. for (int i = 0; i < argc; i++) {
  15. count += ft_strlen(argv[i]);
  16. }
  17.  
  18. // Cria a nova string que será retornada.
  19. char *newString = (char *) malloc(count);
  20.  
  21. // Copia as strings para o newString.
  22. // Usa aux para percorrer o espaço de memória de newString.
  23. char *aux = newString;
  24. for (int i = 0; i < argc; i++) {
  25. for (int j = 0; argv[i][j]; j++, aux++) {
  26. aux[0] = argv[i][j];
  27. }
  28. }
  29.  
  30. // Adiciona o terminador nulo.
  31. aux[0] = 0;
  32.  
  33. // Terminamos.
  34. return newString;
  35. }
  36.  
  37. int main(void) {
  38. const char *strings1[] = {"banana", "pera", "uva"};
  39. char *a = ft_concat_params(3, strings1);
  40. printf("[%s] - %d\n", a, ft_strlen(a));
  41. free(a);
  42.  
  43. const char *strings2[] = {"", "teste", "", "mais", "", "perigoso", ""};
  44. char *b = ft_concat_params(7, strings2);
  45. printf("[%s] - %d\n", b, ft_strlen(b));
  46. free(b);
  47.  
  48. const char *strings3[] = {"", "", ""};
  49. char *c = ft_concat_params(3, strings3);
  50. printf("[%s] - %d\n", c, ft_strlen(c));
  51. free(c);
  52.  
  53. const char *strings4[] = {};
  54. char *d = ft_concat_params(0, strings4);
  55. printf("[%s] - %d\n", d, ft_strlen(d));
  56. free(d);
  57.  
  58. return 0;
  59. }
  60.  
Success #stdin #stdout 0s 9424KB
stdin
Standard input is empty
stdout
[bananaperauva] - 13
[testemaisperigoso] - 17
[] - 0
[] - 0