I’m using a global variable z as a counter. Is there a way to use MyStruct len as my counter instead? I would prefer not to use a global variable.
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <glib.h>
typedef struct st {
char *key;
char *str;
int len;
} MyStruct;
int z = 0;
static void hash2struct (gpointer key, gpointer value, gpointer data) {
MyStruct **s = data;
gchar *k = (gchar *) key;
gchar *h = (gchar *) value;
s[z]->key = strdup(k);
s[z]->str =strdup(h);
z++;
}
int main(int argc, char *argv[]){
int i;
GHashTable *hash = g_hash_table_new(g_str_hash, g_str_equal);
g_hash_table_insert(hash, "Virginia", "Richmond");
g_hash_table_insert(hash, "Texas", "Austin");
g_hash_table_insert(hash, "Ohio", "Columbus");
MyStruct **s = malloc(sizeof(MyStruct) * 3);
for(i = 0; i < 3; i++) {
s[i] = malloc(sizeof(MyStruct));
}
g_hash_table_foreach(hash, hash2struct, s);
for(i = 0; i < 3; i++)
printf("%s %s\n", s[i]->str, s[i]->key);
for(i = 0; i < 3; i++) {
free(s[i]->str);
free(s[i]->key);
free(s[i]);
}
free(s);
g_hash_table_destroy(hash);
return 0;
}
You are presumably envisioning
zas keeping track of the number of cells used in the allocated array. If you tried to stick the value into the individualMyStructs you would risk multiple different values.Instead consider that you could package up the array and it’s counter (in effect building a dynamic array type):
They you keep one instance of this thing and pass that to your
hash2structroutine.