我正在尝试创建一个可以接受任何键值类型的节点。到目前为止,当我使用它一次时它可以工作,但是当我再次使用它时,我会收到错误。
以下是我编写的代码:
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/