2

我正在尝试制作一个可以接受任何键值类型的节点。到目前为止,当我使用它一次时它可以工作,但是当我再次使用它时,我得到了错误。

以下是我编写的代码:

map.h

#ifndef Data_Structures_map_h
#define Data_Structures_map_h

#include <stdio.h>
#include <stdlib.h>

#define node(key_t, value_t)    \
    typedef struct node {       \
        key_t key;              \
        value_t value;          \
    } node

#endif /* Data_Structures_map_h */

main.c

#include <stdio.h>

#include "map.h"

int main(int argc, const char * argv[]) {
    node(char*, int);
    node* n = malloc(sizeof(node*));
    n->key = "first";
    n->value = 1;

    printf("the node n has a key of %s and a value of %d.\n", n->key, n->value);

    // error starts from here
    node(char, char*);
    node* n2 = malloc(sizeof(node*));
    n2->key = 'a';
    n2->value = "first";

    printf("the node n2 has a key of %c and value of %s.\n", n2->key, n2->value);

    return 0;
}

我应该怎么做才能让它工作?

编辑:

错误是Redefinition of 'node',其余的是警告。我正在使用 Xcode。

4

2 回答 2

3

您的问题是您在struct node第二次使用宏时重新定义了。您需要以某种方式确保所有结构都具有唯一的名称。否则编译器会抱怨conflicting typesredefinition of structs这里所见

示例

#include <stdio.h>
#include <string.h>

#define node(name, key_t, value_t)    \
    typedef struct  {                 \
        key_t key;                    \
        value_t value;                \
    } name;                           \

int main(int argc, const char * argv[]) {
    node(stringIntNode, char*, int);
    stringIntNode* n = malloc(sizeof(*n));
    n->key = "first";
    n->value = 1;

    printf("the node n has a key of %s and a value of %d.\n", n->key, n->value);

    node(charStringNode, char, char*);
    charStringNode* n2 = malloc(sizeof(*n2));
    n2->key = 'a';
    n2->value = "first";

    printf("the node n2 has a key of %c and value of %s.\n", n2->key, n2->value);

    return 0;
}

输出:

节点 n 的键为 first,值为 1。

节点 n2 的键为 a,值为 first。

于 2013-06-18T17:26:56.343 回答
1
#include <stdio.h>
#include <stdlib.h>

typedef struct node {
    void *key;
    void *value;
} node;

static void *_vp;
#define box(type, value) (_vp = malloc(sizeof(type)), *(type*)_vp=value, _vp)
#define unbox(type, obj) (*(type*)obj)

int main(void) {
    node* n = malloc(sizeof(node));
    n->key = "first";//Reference type as it is
    n->value = box(int, 1);//Value type boxing

    //Reference type cast, Value type unboxing
    printf("the node n has a key of %s and a value of %d.\n", (char*)n->key, unbox(int, n->value));

    node* n2 = malloc(sizeof(node));
    n2->key   = box(char, 'a');
    n2->value = "first";

    printf("the node n2 has a key of %c and value of %s.\n", unbox(char, n2->key), (char*)n2->value);

    return 0;
}
于 2013-06-18T17:42:27.853 回答