home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1993 #1 / NN_1993_1.iso / spool / comp / lang / c / 19247 < prev    next >
Encoding:
Text File  |  1993-01-05  |  1.9 KB  |  62 lines

  1. Path: sparky!uunet!pipex!bnr.co.uk!uknet!warwick!coventry!champion
  2. From: champion@cch.coventry.ac.uk (Alun)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Need help with string arrays
  5. Message-ID: <C0DLwq.n3@cck.coventry.ac.uk>
  6. Date: 5 Jan 93 10:17:13 GMT
  7. References: <1992Dec27.232512.22474@news.ysu.edu>
  8. Sender: news@cck.coventry.ac.uk (news user)
  9. Organization: Coventry University, Coventry, UK.
  10. Lines: 49
  11. Nntp-Posting-Host: cc_sysh
  12.  
  13. In article <1992Dec27.232512.22474@news.ysu.edu> ah017@yfn.ysu.edu (John B. Lee) writes:
  14. ~
  15. ~In a current program that I am writing I have an array declaration
  16. ~that looks like this:
  17. ~
  18. ~char names[][4];
  19. ~
  20. ~How would I use the gets() function to put a string into this array.
  21. ~Am I declaring the array correctly to receive five strings?  << This
  22. ~is what I'm trying to do.
  23. ~
  24.  
  25. No you are not declaring it correctly.
  26. char names[][5];
  27. /* Declares an array of 5 (from 0 to 4) arrays of characters */
  28.  
  29. Personally I would declare this as
  30. char *names[5];
  31.  
  32. but you must remember that gets() is not good - it does nothing about bounds
  33. checking. If you type a name longer than the allocated memory then gets() will
  34. corrupt your program.
  35.  
  36. Use fgets
  37.  
  38. Example: (Not a very good one)
  39.  
  40. int i;
  41. char *names[5];                         /* 5 Names */
  42. char buf[MAX_NAME_SIZE + 1];            /* fgets() appends a '\0' */
  43.  
  44. for(i = 0; i < 5; i++) {
  45.     fgets(buf, MAX_NAME_SIZE, stdin);
  46.     if(buf[strlen(buf) - 1] == '\n')
  47.         buf[strlen(buf) - 1] == '\0';
  48.     names[i] = malloc(sizeof(char) * (strlen(buf) + 1)); /* Test! Test! Test! */
  49.     strcpy(names[i], buf);
  50. }
  51.     
  52.  
  53. Hope this helps
  54.  
  55.   -Alun
  56.   
  57. -- 
  58.   *I'm as bad as the worst - but thank God(?) I am as good as the best.*
  59.     *People who think they know everything annoy those of us that do.*
  60. A.Champion                |  That's an interesting point, in the sense of
  61. (champion@uk.ac.cov.cch)  |    being very not interesting at all. - The Liar
  62.