Advertisement
mcgizmo

Untitled

Nov 23rd, 2016
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.02 KB | None | 0 0
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. #include<string.h>
  4. #define N 20
  5.  
  6.  
  7. char *get_string(char *str) // the function what allocate memory for the same string, and copy the string section in to the new string and print it.
  8. {
  9. int length;
  10. char *new_str;
  11.  
  12. if (!str) // return a null pointer (0) if there is no available memory or if the arena has been detectably corrupted by storing outside the bounds of a block
  13. {
  14. printf("Error!Not enough memory!\n");
  15. exit(1);
  16. }
  17.  
  18. else
  19. {
  20. length = strlen(str);
  21. new_str = (char*)malloc(sizeof(char)*(length + 1)); // Initial memory allocation, memory allocated using malloc
  22. strcpy(new_str, str);
  23. return new_str; // The return value of the function.
  24. }
  25. }
  26. void main()
  27. {
  28.  
  29. char str[N], *new_str;
  30. printf("Please enter a string: ");
  31. scanf("%s", str);
  32. new_str = get_string(str);
  33. printf("The new string from the function is: %s\n", new_str); // printing a value of the new function
  34.  
  35.  
  36. free(new_str); // done with the int objects, and free the associated pointer
  37.  
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement