arrays and structures in C
    Pablo Halpern 
    pablo at polygen.uucp
       
    Wed Apr 20 08:00:05 AEST 1988
    
    
  
>From article <12983 at brl-adm.ARPA>, by jfjr at mitre-bedford.arpa (Freedman):
> Alternatively you could declare  
> 
> typedef rather_large_type large_array[some_large_integer];
> 
> but I haven't had much luck with malloc(sizeof(large_array))
> 
> Now I can do this
> 
> typedef struct {
>           int dummy_field;
>           large_array large;
>           } large_structure;
> 
> malloc(sizeof(large_structure)) 
> 
> this seems to work and looks more portable than anything else but
> its not pretty. Have I missed something??
Your first alternative:
	typedef rather_large_type large_array[some_large_integer];
	pointer = (rather_large_type *) malloc(sizeof(large_array));
SHOULD work but doesn't on some compilers which don't understand that
an array is NOT a pointer, an array is CONVERTED to a pointer when
indexed or de-referenced.
Assuming you can't change to a better compiler, I suggest a slight varient
on your second attempt:
	typedef struct {
		large_array	large;
		char		dummy_field;
	} large_structure;
	pointer = (rather_large_type *) malloc(sizeof(large_structure));
That way, you can simply say:
	pointer[index]
instead of 
	pointer->large[index]
(Every compiler I know of the address of a struct is the same as the address
of its first element.  dpANS requires this.)
However, I don't understand your objection to:
	pointer = (rather_large_type *) malloc(some_large_integer * 
					       sizeof(rather_large_type));
Which seems the same to me.
Pablo Halpern		|	mit-eddie \
Polygen Corp.		|	princeton  \ !polygen!pablo  (UUCP)
200 Fifth Ave.		|	bu-cs      /
Waltham, MA 02254	|	stellar   /
    
    
More information about the Comp.lang.c
mailing list