Advertisement
quantim

String_Question_1

Dec 19th, 2015
196
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.17 KB | None | 0 0
  1. ################################## DOES NOT WORK ######################################################
  2. #
  3. #   Output:
  4. # gcc -Wall -Wextra -std=c11 crap.c -o crap.o
  5. # crap.c: In function ‘main’:
  6. # crap.c:10:7: warning: ‘firstName’ is used uninitialized in this function [-Wuninitialized]
  7. #   scanf("%s", firstName);
  8. #        ^
  9. # crap.c:12:7: warning: ‘lastName’ is used uninitialized in this function [-Wuninitialized]
  10. #   scanf("%s", lastName);
  11. #        ^
  12. #######################################################################################################
  13.  
  14. #include <stdio.h>
  15.  
  16. int main(void)
  17. {
  18.  
  19.         char * firstName;
  20.         char * lastName;
  21.  
  22.         printf("What is your first name?\n");
  23.         scanf("%s", firstName);
  24.         printf("What is your last name?\n");
  25.         scanf("%s", lastName);
  26.  
  27.         printf("Your full name is %s %s\n", firstName, lastName);
  28.        
  29.         return(0);
  30. }
  31.  
  32. ####################### WORKS #####################################
  33. #include <stdio.h>
  34.  
  35. int main(void)
  36. {
  37.  
  38.         char firstName[20];
  39.         char lastName[20];
  40.  
  41.         printf("What is your first name?\n");
  42.         scanf("%s", firstName);
  43.         printf("What is your last name?\n");
  44.         scanf("%s", lastName);
  45.  
  46.         printf("Your full name is %s %s\n", firstName, lastName);
  47.        
  48.         return(0);
  49. }
  50.  
  51. ###################### THIS ALSO WORKS ###############################
  52. #include <stdio.h>
  53. #include <stdlib.h>
  54.  
  55. int main(void)
  56. {      
  57.         char * firstName;
  58.         char * lastName;
  59.         /*
  60.         * Curretly, firstName and lastName do not have any space
  61.         * reserved in memory. Therefore we cannot save any variables to
  62.         * the location they point to.
  63.         */
  64.  
  65.         // Allocate 20 bytes. Don't forget to free.
  66.         firstName = (char *) malloc(20);
  67.         lastName = (char *) malloc(20);
  68.  
  69.         printf("What is your first name?\n");
  70.         scanf("%s", firstName);
  71.         printf("What is your last name?\n");
  72.         scanf("%s", lastName);
  73.  
  74.         printf("Your full name is %s %s\n", firstName, lastName);
  75.        
  76.         free(firstName);
  77.         free(lastName);
  78.         return(0);
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement