Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
| From | Ian Collins <ian-news@hotmail.com> |
|---|---|
| Newsgroups | comp.lang.c |
| Subject | Re: How to write own function to allocation a set of structures? |
| Date | 2012-03-20 15:50 +1300 |
| Message-ID | <9sq9k5FuerU3@mid.individual.net> (permalink) |
| References | <354bb461-708b-4ce5-99ad-ab0b37872797@x10g2000pbi.googlegroups.com> |
On 03/20/12 03:32 PM, Martin De Kauwe wrote:
> Hi,
>
> I currently allocate a series of structures...
>
> in the .h file
>
> typedef struct {
> FILE *in_fp;
> etc....
> } control_struct;
>
> then in the main func:
>
> control_struct *ctrl;
> if ((ctrl = malloc(sizeof(control_struct))) == NULL) {
> fprintf(stderr, "control structure: Not allocated enough memory
> \n");
> exit(EXIT_FAILURE);
> }
>
> I would like to write my own generic function to take the malloc
> section to tidy up the code (as I have a number of structures to
> allocate), i.e. so instead in the main I would have something like
>
> allocate_structure(&ctrl);
>
> and
>
> void allocate_structure(structure *s) {
> if ((s = malloc(sizeof(structure))) == NULL) {
> fprintf(stderr, "Structure: Not allocated enough memory\n");
> exit(EXIT_FAILURE);
> }
> }
>
> But I am not sure how to pass the structure when it is unallocated,
> i.e. how to set up the function declarations.
Either return the value allocated, or pass a pointer to the pointer:
structure* allocate_structure()
{
structure* s = malloc(sizeof *s);
//error check
return s;
}
Or
void allocate_structure( structure** s )
{
*s = malloc(sizeof *s);
//error check
}
--
Ian Collins
Back to comp.lang.c | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
How to write own function to allocation a set of structures? Martin De Kauwe <mdekauwe@gmail.com> - 2012-03-19 19:32 -0700
Re: How to write own function to allocation a set of structures? Ian Collins <ian-news@hotmail.com> - 2012-03-20 15:50 +1300
Re: How to write own function to allocation a set of structures? Barry Schwarz <schwarzb@dqel.com> - 2012-03-19 20:14 -0700
Re: How to write own function to allocation a set of structures? Martin De Kauwe <mdekauwe@gmail.com> - 2012-03-19 23:58 -0700
Re: How to write own function to allocation a set of structures? Ian Collins <ian-news@hotmail.com> - 2012-03-20 21:13 +1300
Re: How to write own function to allocation a set of structures? Martin De Kauwe <mdekauwe@gmail.com> - 2012-03-20 02:32 -0700
Re: How to write own function to allocation a set of structures? Ben Bacarisse <ben.usenet@bsb.me.uk> - 2012-03-20 13:06 +0000
Re: How to write own function to allocation a set of structures? ImpalerCore <jadill33@gmail.com> - 2012-03-20 07:27 -0700
csiph-web