"hal" <z3****@gmail.comwrote in message news:
I'm trying to make an array of pointers to 'TwoCounts' structs, where
the size of the array is arraySize. Right now I'm just mallocing
enough space for all the pointers to the structs, and mallocing space
for the pointer 'countPtr' in each struct, but do I need to do
anything else? Thanks.
typedef struct TwoCounts {
int *countPtr;
int count;
} TwoCounts;
int j;
TwoCounts *twoCountsArray;
TwoCounts *tempPtr;
twoCountsArray = (TwoCounts *) malloc(arraySize * sizeof(TwoCounts
*));
for (j=0;j<arraySize;j++){
//get location of each pointer in the array
tempPtr = (twoCountsArray + arraySize * sizeof(TwoCounts *));
//initialize the countPtr
tempPtr->countPtr = (TwoCounts *) malloc (sizeof(int));
*(tempPtr->countPtr) = NULL;
}
No, you've got it wrong.
First a style issue. You've got a member named countPtr and member named
count. Then you call the struct TwoCounts. This is highly confusing, and I
can't actually work out what is intended.
If you want an arbitrary-length list of integers, call the count member "N"
and call the pointer "ptr" if the structure is a generic list of integers,
"counts" if you use it only for storing counts specifically. Better still,
say what you are counting.
twoCountsArray is a pointer that points to a buffer containing TwoCounts
structs, laid out contiguously in memory. So you need to say
twoCountsArray = (TwoCounts *) malloc( ArraySize * sizeof(TwoCounts) );
Not sizeof a pointer, sizeof the structure.
you don't actually need the cast, and some people will recommend sizeof
*twoCountsArray rather than sizeof(TwoCounts), although these points are a
bit contentious.
Now you want to intialise the array of structures you have created. So use
array notation
for(j=0;j<ArraySize;j++)
{
twoCountsArray[j].count = 1;
twoCountsArray[j].countPtr = malloc(sizeof(int));
twoCountsArray[i].countPtr[0] = 0;
}
I presume here that you want to initialise the structures to list of one
integer, which starts off with a value of zero.
There's no need to mess about with temporary pointers. Array notation is
much less confusing.
--
Free games and programming goodies.
http://www.personal.leeds.ac.uk/~bgy1mm