home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #27 / NN_1992_27.iso / spool / comp / lang / c / 16820 < prev    next >
Encoding:
Text File  |  1992-11-19  |  1.8 KB  |  64 lines

  1. Path: sparky!uunet!wupost!gumby!destroyer!ncar!hsdndev!marby
  2. From: marby@laura.harvard.edu (Craig Marby)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: How to malloc an array of pointers?
  5. Message-ID: <MARBY.92Nov19152148@laura.harvard.edu>
  6. Date: 19 Nov 92 20:21:48 GMT
  7. References: <1992Nov19.004950.9200@icaen.uiowa.edu> <Bxyv6B.5FL@portal.hq.videocart.com>
  8. Sender: usenet@hsdndev.UUCP
  9. Organization: Chemistry Dept., Harvard University
  10. Lines: 51
  11. In-reply-to: dfuller@portal.hq.videocart.com's message of 19 Nov 92 14:06:10 GMT
  12.  
  13. sbtaves@icaen.uiowa.edu (Steven Bradley Taves) writes:
  14. : Hi all,
  15. :     I'd appreciate it if someone could tell me how I can allocate memory
  16. : for an array of pointers and for the strings they will be pointing to.
  17. : I have  
  18. :        char *Var[];
  19. : Normally for
  20. :        char *Var;
  21. : you do
  22. :        Var=(char *)malloc(10*sizeof(char));
  23. : for a string of 10 characters.
  24. : I want to allocate memory for 10 strings of ten characters.  Also, how
  25. : do I allocate memory for the pointers themselves?
  26.  
  27. > On 19 Nov 14:06:10 GMT, dfuller@portal.hq.videocart.com (Dave Fuller) said:
  28. Dave> try this:
  29.  
  30. Dave> instead of char *Var[] -> char *Var[10]  (since you know you have 10)
  31. Dave> this will also allocate the memory for you automatically (for pointers)
  32.  
  33. Dave> then without any error checking of course
  34.  
  35. Dave> for (i = 0; i < 10; i++)
  36. Dave>    Var[i] = (char *) malloc(10 * sizeof(char));
  37.  
  38. Below is sample code that at run-time can handle a variable number
  39. of strings for those who are interested.
  40.  
  41. #define STRING_COUNT  10
  42. #define STRING_LENGTH 10
  43. main()
  44. {
  45.    int i;
  46.    char *(*Var)[];
  47.  
  48.    Var = (char *(*)[]) malloc(STRING_COUNT);
  49.  
  50.    for (i = 0; i < STRING_COUNT; i++)
  51.       (*Var)[i] = (char *) malloc(STRING_LENGTH);
  52. }
  53. --
  54.  
  55.     __o         
  56.   _ \<,_       Craig A. Marby    marby@layla.harvard.edu
  57.  (_)/ (_)      
  58. ~~~~~~~~~~
  59.