<分区>
我想知道如何 malloc(然后重新分配)一个结构数组。 这是我的结构:
typedef struct tag {
char *key;
char *val;
} tag;
我在另一个结构中使用这个结构:
typedef struct node {
int id;
double lat;
double lon;
int visible;
tag *tab;
} node;
我定义了一个node *n
,然后:
n->tab = (tag*)malloc(sizeof(tag) * 5);
但是我有一个错误,malloc corruption
。
void remplisTag(xmlNodePtr cur, node *n) {
xmlNodePtr fils;
n->tab = malloc(sizeof(*n->tab) * 5);
if (n->tab == NULL) {
error(E_ERROR_MALLOC);
}
printf("apres malloc\n");
int taille = 5;
int ind = 0;
xmlAttrPtr attr1, attr2;
xmlChar *key;
xmlChar *value;
fils = cur->xmlChildrenNode;
fils = fils->next;
while (xmlStrcmp(fils->name, (const xmlChar*)"text") != 0) {
if (xmlStrcmp(fils->name, (const xmlChar*)"tag") == 0) {
if (ind == taille - 1) {
n->tab = realloc(n->tab, sizeof(tag) * (taille + 5));
taille = taille + 5;
} else {
taille = taille;
}
/* searching for key */
attr1 = xmlHasProp(fils, (const xmlChar*)"k");
if (attr1 == NULL) {
error(E_KEY);
} else {
key = xmlGetProp(fils, (const xmlChar*)"k");
if (key == NULL) {
error(E_KEY_V);
}
/* searching for value */
attr2 = xmlHasProp(fils, (const xmlChar*)"v");
if (attr2 == NULL) {
error(E_VALUE);
}
value = xmlGetProp(fils, (const xmlChar*)"v");
if (value == NULL) {
error(E_VALUE_V);
}
tag t;
t.key = malloc(sizeof((char*)key));
strcpy(t.key, (char*)key);
strcpy(t.val, (char*)value);
t.val = malloc(sizeof((char*)value));
n->tab[ind++] = t;
}
}
fils = fils->next;
}
free(n->tab);
}
在 main
中:
node *n = malloc(sizeof(node));
xmlNodePtr cur;
在 while
循环中:
remplisTag(cur, n);