节点的C函数宏

标签 c dictionary macros struct nodes

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

以下是我编写的代码:

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;
}

我应该怎么做才能让它发挥作用?

编辑:

错误是重新定义'node',其余的是警告。 我正在使用 Xcode。

最佳答案

您的问题是,当您第二次使用该宏时,您正在重新定义结构节点。您需要以某种方式确保所有结构都具有唯一的名称。否则,编译器会提示类型冲突结构重新定义seen here .

<强> Example :

#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;
}

输出:

the node n has a key of first and a value of 1.

the node n2 has a key of a and value of first.

关于节点的C函数宏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17175009/

相关文章:

javascript - 将js数组转换为字典映射

c++ - 如何柯里化(Currying) C/C++ 宏?

c - 如何在configure.ac中使用宏__GNUC__和__GNUC_MINOR__

c - fscanf : how to read but not assign commas?

c - 一个 friend 给我发了一段我不明白的片段。这是如何运作的?

c - for循环中的printf语句

python - 读取多个 hdf5 文件并将它们附加到新字典

c - 堆对象的指定初始化器

python - 如何制作具有多个列表的字典

c++ - 每次编译cuda源码时md5sum的值都会变化