#include <stdio.h> #include <stdlib.h> typedef struct name_val { char *name; int value; } name_val; typedef struct name_val_table { int n_val; int max; name_val *nv; } name_val_table; name_val_table nv_tab; enum { NVINIT = 1, NVGROW = 2 }; /* add new name and value to nv_tab */ int add_name_val(name_val nv) { name_val *nvp; if (nv_tab.nv == NULL) { /* first time */ nv_tab.nv = malloc(NVINIT * sizeof(name_val)); if (nv_tab.nv == NULL) /* malloc failed */ return -1; nv_tab.max = NVINIT; nv_tab.n_val = 0; } else if (nv_tab.n_val >= nv_tab.max) { /* grow */ nvp = realloc(nv_tab.nv, NVGROW * nv_tab.max * sizeof(name_val)); if (nvp == NULL) /* realloc failed */ return -1; nv_tab.nv = nvp; nv_tab.max *= NVGROW; } nv_tab.nv[nv_tab.n_val] = nv; return nv_tab.n_val++; } int main() { int i; name_val nv1 = { "I", 1 }; name_val nv2 = { "love", 2 }; name_val nv3 = { "you", 3 }; add_name_val(nv1); add_name_val(nv2); add_name_val(nv3); for (i = 0; i < nv_tab.n_val; ++i) printf("%s/n", nv_tab.nv[i].name); return 0; }