I have a struct containing deep nesting of ptrs to related structs that also contain pointers. I am having issues getting the initialization right because the array of ptrs must have size passed to the init function. See code below:
typedefs:
typedef struct tuple Tuple;
typedef struct dict Dict;
int findKey(Dict *d, char *check);
struct tuple {
char *key; //named loc
void *val; //data
};
struct dict {
unsigned int size; //max size
unsigned int counter; //# tuples
Tuple **entries; //list of tuples
};
init func:
Dict *initDict(const unsigned int size) {
Dict data = {.size = size, .counter = 0, .entries = (Tuple**) malloc(sizeof(Tuple*) * size)};
for (unsigned int i = 0; i < size; i++) {
data.entries[i] = (Tuple*) malloc(sizeof(Tuple));
data.entries[i]->key = '\0'; /* initially null */
data.entries[i]->val = '\0'; /* initially null */
}
Dict *d = (Dict*) malloc(sizeof(Dict));
d = &data;
return d;
}
Dict ops:
short setTuple(Dict *d, char *key, void* val) {
int i;
if ((i = findKey(d, key)) != -1) { /* found key */
d->entries[i]->val = val;
return 0;
}
else { /* new entry */
if (d->counter < d->size) { /* find first null */
for (unsigned int i = 0; i < d->size; i++) {
if (d->entries[i]->key == NULL) break;
} /* then replace null slot */
d->entries[i]->key = (char *) malloc(sizeof(char) * strlen(key));
d->entries[i]->key = key;
d->entries[i]->val = (void *) malloc(sizeof(&val));
d->entries[i]->val = val;
d->counter++;
return 0;
}
return -1; /* no room */
}
}
short setTuples(Dict *d, char *json) {
}
void* getTuple(Dict *d, char *key) {
int i;
if ((i = findKey(d, key)) != -1) {
void *val = d->entries[i]->val;
return val;
} return (void *) -1; /* not found */
}
void* getIndex(Dict *d, unsigned int index) {
if (index < d->counter && d->entries[index]->key != NULL) {
void *val = d->entries[index]->val;
return val;
} return (void *) -1; /* not found */
}
/* TODO: add checks for NULL ptr prior to freeing? */
int removeTuple(Dict *d, char *key) {
int i;
if ((i = findKey(d, key)) != -1) {
free(d->entries[i]->key);
free(d->entries[i]->val);
free(d->entries[i]);
d->entries[i]->key = '\0';
d->entries[i]->val = '\0';
d->counter--;
return 0;
} return -1; /* no room */
}
void destroyDict(Dict *d) {
for (unsigned int i = 0; i < d->counter; i++) {
free(d->entries[i]->key);
free(d->entries[i]->val);
free(d->entries[i]);
d->entries[i]->key = '\0';
d->entries[i]->val = '\0';
d->entries[i] = '\0';
d->counter--;
}
free(d->entries);
free(d);
}
/* return index of tuple in dict or -1 if DNE */
int findKey(Dict* d, char* check) {
unsigned int i;
for (i = 0; i < d->counter; i++) {
if (d->entries[i]->key != NULL && strcmp(d->entries[i]->key, check) == 0) {
return i;
}
} return -1; /* not found */
}