Advertisement
xeritt

Ввод массива(статический, динамический) строк через fgets

Nov 9th, 2016
247
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.18 KB | None | 0 0
  1. /*
  2.   gcc  std=c99  -Wall -o main main.c
  3.  */
  4.  
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7. #include <string.h>
  8. #define MAX_LEN 1024
  9.  
  10. void readString(char *buf){
  11.     fgets(buf, MAX_LEN, stdin);
  12. }  
  13.  
  14. void readStrings(char buf[][MAX_LEN], int count){
  15.     for (int i = 0; i < count ; i++){
  16.         readString(buf[i]);
  17.     }
  18. }  
  19.  
  20. void printSrings(char buf[][MAX_LEN], int count){
  21.     for (int i = 0; i < count ; i++){
  22.         printf("%s", buf[i]);
  23.     }
  24. }
  25.  
  26.  
  27. void readStringsDyn(char **buf, int count){
  28.     char buffer[MAX_LEN];
  29.     for (int i = 0; i < count ; i++){
  30.         readString(buffer);
  31.         buf[i] = (char *)malloc(sizeof(char)*strlen(buffer));
  32.         strcpy(buf[i], buffer);
  33.     }
  34. }  
  35.  
  36. void printSringsDyn(char **buf, int count){
  37.     for (int i = 0; i < count ; i++){
  38.         printf("%s", buf[i]);
  39.     }
  40. }
  41.    
  42. int main(int argc, char **argv){
  43.     int count = 3;
  44.     scanf("%d\n", &count);
  45.     char mas[count][MAX_LEN];//c99 или выше стандарт
  46.     readStrings(mas, count);
  47.     printSrings(mas, count);
  48.    
  49.    
  50.     char **masDyn;
  51.     masDyn = (char **)malloc(sizeof(char *)*count);
  52.     readStringsDyn(masDyn, count);
  53.     printSringsDyn(masDyn, count);
  54.     for (int i = 0; i < count; i++)
  55.     {
  56.         free(masDyn[i]);
  57.     }
  58.     free(masDyn);
  59.     return 0;
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement