I have been working on a DisjointSet assignment in C for a couple days now. I understand the functions find (w/ and w/o path compression), using rank in the function link when performing the union on a set. But I am having issues with C syntax.
We have to make an array of records containing the rank and the key for the set. so my struct looks as:
typedef struct DisjointSet_t {
int data;
int key;
} DisjointSet;
My problem is declaring the array to manipulate the set. There is something wrong with me initializing the array for the set. Here's the snippet of the CreateSet code:
static DisjointSet *S;
voi开发者_运维问答d CreateSet(int numElements){
DisjointSet *t;
if (numElements > 0){
t = (DisjointSet *)malloc(sizeof(DisjointSet));
}
if(S != NULL){
S = t[numElements+1];
}
}
If I implemented this in Java I think it'd be a little easier. How can I improve this? Am I missing something about understanding how to initializing class arrays in C?
Hmmm ... with
malloc(sizeof(DisjointSet))
you reserve space for one object of type DisjointSet. To allocate space for 20 objects you need to multiply ...
malloc(20 * sizeof(DisjointSet))
and, once you have 20 objects, in an array, the array goes from 0 to 19.
If you're trying to allocate an array, you need to allocate space for all array elements: malloc(sizeof(DisjointSet) * numElements)
.
Also, you can assign S as Jeremy Simon describes.
Variables S and t are both of type DisjointSet* so you should be able to just assign t to S.
if (S != NULL)
{
S = t;
}
Also you need to initialise the static S to NULL
static DisjointSet *S = NULL;
精彩评论