home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!wupost!gumby!destroyer!ncar!hsdndev!marby
- From: marby@laura.harvard.edu (Craig Marby)
- Newsgroups: comp.lang.c
- Subject: Re: How to malloc an array of pointers?
- Message-ID: <MARBY.92Nov19152148@laura.harvard.edu>
- Date: 19 Nov 92 20:21:48 GMT
- References: <1992Nov19.004950.9200@icaen.uiowa.edu> <Bxyv6B.5FL@portal.hq.videocart.com>
- Sender: usenet@hsdndev.UUCP
- Organization: Chemistry Dept., Harvard University
- Lines: 51
- In-reply-to: dfuller@portal.hq.videocart.com's message of 19 Nov 92 14:06:10 GMT
-
- sbtaves@icaen.uiowa.edu (Steven Bradley Taves) writes:
- : Hi all,
- :
- : I'd appreciate it if someone could tell me how I can allocate memory
- : for an array of pointers and for the strings they will be pointing to.
- :
- : I have
- : char *Var[];
- :
- : Normally for
- : char *Var;
- : you do
- : Var=(char *)malloc(10*sizeof(char));
- : for a string of 10 characters.
- :
- : I want to allocate memory for 10 strings of ten characters. Also, how
- : do I allocate memory for the pointers themselves?
- :
-
- > On 19 Nov 14:06:10 GMT, dfuller@portal.hq.videocart.com (Dave Fuller) said:
- Dave> try this:
-
- Dave> instead of char *Var[] -> char *Var[10] (since you know you have 10)
- Dave> this will also allocate the memory for you automatically (for pointers)
-
- Dave> then without any error checking of course
-
- Dave> for (i = 0; i < 10; i++)
- Dave> Var[i] = (char *) malloc(10 * sizeof(char));
-
- Below is sample code that at run-time can handle a variable number
- of strings for those who are interested.
-
- #define STRING_COUNT 10
- #define STRING_LENGTH 10
- main()
- {
- int i;
- char *(*Var)[];
-
- Var = (char *(*)[]) malloc(STRING_COUNT);
-
- for (i = 0; i < STRING_COUNT; i++)
- (*Var)[i] = (char *) malloc(STRING_LENGTH);
- }
- --
-
- __o
- _ \<,_ Craig A. Marby marby@layla.harvard.edu
- (_)/ (_)
- ~~~~~~~~~~
-