Advertisement
dmilicev

dynamic_memory_allocation_for strings.c

Jan 15th, 2020
631
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.54 KB | None
  1. /*
  2.  
  3.     dynamic_memory_allocation_for strings.c
  4.  
  5. The C function fgets () is deprecated and discontinued in 2011.
  6.  
  7. gets() is risky to use!
  8. https://www.geeksforgeeks.org/gets-is-risky-to-use/
  9.  
  10. Thanks for the suggestions to
  11. Jark Clim
  12. https://www.facebook.com/metallicsoul92
  13. and
  14. Alan Sampson
  15. https://www.facebook.com/alansamps
  16.  
  17. I did a program update and used the fgets() function
  18. instead of the gets() function.
  19.  
  20. char *gets(char *str)
  21. https://www.tutorialspoint.com/c_standard_library/c_function_gets.htm
  22.  
  23. char *fgets(char *str, int n, FILE *stream)
  24. https://www.tutorialspoint.com/c_standard_library/c_function_fgets.htm
  25.  
  26.  
  27. Before each call of function fgets()
  28. we must reserve memory for the string str[i].
  29.  
  30.  
  31.     You can find all my C programs at Dragan Milicev's pastebin:
  32.  
  33.     https://pastebin.com/u/dmilicev
  34.  
  35.     https://www.facebook.com/dmilicev
  36.  
  37. */
  38.  
  39. #include <stdio.h>
  40. #include <stdlib.h> // for malloc(), calloc(), realloc(), free()
  41. #include <string.h> // for string functions
  42.  
  43. #define LEN 255
  44.  
  45. int main(void)
  46. {
  47.     int i;
  48.     char *str[3];   // here is 3 pointers to strings
  49.  
  50.     for(i=0;i<3;i++)
  51.     {
  52.         // reserve memory space (length LEN characters) to make room for str[i]
  53.         str[i] = malloc( LEN * sizeof(char) );
  54.  
  55.         // Checking whether memory reallocation succeeded
  56.         if( str[i] == NULL )
  57.         {
  58.             fprintf(stderr, "\n\n malloc() for str[%d] error! \n\n", i);
  59.             exit(EXIT_FAILURE);
  60.         }
  61.  
  62.         printf("\n Enter a string: ");
  63.         fgets( str[i], LEN, stdin );
  64.  
  65.         printf("\n You entered: %s \n", str[i]);
  66.     }
  67.  
  68.     return(0);
  69.  
  70. } // main()
Advertisement
RAW Paste Data Copied
Advertisement