Koster <koster_thomas@yahoo.com.sg> wrote:[color=blue]
> I have a question about the appropriateness of calloc. Consider an array of
> pointers to structs which need to be allocated space on the heap, for example:[/color]
Where the system will allocate space for you shouldn't be of any
concern for you as long as you're writing portable C;-)
[color=blue]
> typedef struct myStruct *PMYSTRUCT;
> struct myStruct
> {
> int i;
> int j;
> ...etc...
> }[/color]
[color=blue]
> PMYSTRUCT myArray[10];[/color]
[color=blue]
> While I know I can point and allocate each element manually my looping mallocs,
> I wonder if calloc will do what I want. Will executing "myArray = calloc(10,
> sizeof(myStruct));" allocate 10 myStructs somewhere on the heap and put pointers
> to each one in the myArray array, or will it allocate the myStructs and point
> myArray[0] to it, thereby making myArray[1] point somewhere inside the 1st
> myStruct and messing up everything?[/color]
First of all, since you has made PMYSTRUCT to be a *pointer* to
struct myStruct, the line
PMYSTRUCT myArray[10];
will give you an array of ten such *pointers*. It's as if you had written
struct myStruct *myArray[ 10 ];
When you then try to do an assignment as in
myArray = calloc( 10, sizeof( myStruct ) );
your compiler should complain loudly because your 'myArray' can't be
used unadorned as a left hand side value - only when used on the right
hand side or as part of an expression it decays into a pointer to the
first element of the array. So you need either
*myArray = calloc( 10, sizeof( myStruct ) );
or, equivalently,
myArray[ 0 ] = calloc( 10, sizeof( myStruct ) );
to assign to the first element of the array 'myArray'. Of course, when
you do this all the other nine elements will still point to some random
places in memory.
You have two alternatives. First, change the typedef to
typedef struct myStruct PMYSTRUCT;
so that PMYSTRUCT does not translate to a pointer to a myStruct
structures but to 'struct myStruct' itself. Then
PMYSTRUCT myArray[10];
will give you an array of 10 such structures with all memory already
attached, so you don't have to use calloc() or malloc().
Or, if you insist on
typedef struct myStruct *PMYSTRUCT;
use
PMYSTRUCT myArray;
(But then I still would prefer
typeded struct myStruct MYSTRUCT;
MYSTRUCT *myArray;
so you always know if you're dealing with a real structure or a pointer,
instead of having the "pointerness" of it hidden, which in my opinion
makes reading code much more difficult). Then you can allocate memory
with
myArray = calloc( 10, sizeof *myArray );
and you now can treat myArray basically like an array of 10 strutctures,
i.e. you can get at the member 'i' of the 5th structure with
'myArray[ 4 ].i' etc.
Regards, Jens
--
_ _____ _____
| ||_ _||_ _|
Jens.Toerring@physik.fu-berlin.de
_ | | | | | |
| |_| | | | | |
http://www.physik.fu-berlin.de/~toerring
\___/ens|_|homs|_|oerring