Advertisement
Toliak

pureC3

Oct 26th, 2018
329
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.41 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. char *concat(char **s, int n)
  6. {
  7.     unsigned long length = 0;
  8.     for (int i = 0; i < n; i++) {           // Получаем длину итоговой строки
  9.         length += strlen(s[i]);
  10.     }
  11.  
  12.     char *str = (char *)malloc(length);         // Выделяем память для новой строки
  13.     for (int i = 0; i < n; i++) {
  14.         if (i == 0) {
  15.             strcpy(str, s[i]);                  // Инициализируем результирующую строку
  16.         } else {
  17.             strcat(str, s[i]);                  // Дописываем
  18.         }
  19.     }
  20.     return str;
  21. }
  22.  
  23. int main()
  24. {
  25.     int amount;
  26.     scanf("%d\n", &amount);                     // Ввод количества
  27.  
  28.     char **array = (char **)malloc(sizeof(char *) * amount);        // Создаем массив из строк
  29.     for (int i = 0; i < amount; i++) {
  30.         array[i] = (char *)malloc(sizeof(char) * 512);              // Создаем строки
  31.         gets(array[i]);                                         // Читаем
  32.     }
  33.  
  34.     printf("%s\n", concat(array, amount));                      // Печатаем результат
  35.  
  36.     for (int i = 0; i < amount; i++) {                          // Освобождаем память
  37.         free(array[i]);
  38.     }
  39.     free(array);
  40.  
  41.     return 0;
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement