我正在用 C 实现多位 trie。我通常用 JAVA 编写代码,在用 C 声明和初始化 Node 结构时遇到困难。
在Java中,节点是这样的:
private static class Node {
private String nextHop = null;
private Node[] pointer = new Node[(int)Math.pow(2, STRIDE)];
}
在C中,我是这样做的:
#define STRIDE 3
struct MtNode{
/* nodes stores pointers to its 2^stride child nodes.*/
MtNode* nodes; // 2^stride = 2^3 = 8
int nexthop;
};
/* Initialize binary trie node */
MtNode* init_mtnode(){
MtNode *ret = (MtNode *)malloc(sizeof(MtNode));
int size = (int)pow(2,STRIDE);
ret->nodes = (MtNode *)malloc( sizeof(MtNode) * size );
for (int i=0; i<(int)pow(2,STRIDE); ++i)
(ret->nodes[i]) = NULL;
ret->nexthop = -1;
return ret;
}
我在初始化节点时在 init_mtnode() 函数中遇到错误。请帮助并提出正确的实现建议。
最佳答案
#define STRIDE 3
struct MtNode{
/* nodes stores pointers to its 2^stride child nodes.*/
/* you are using C, so struct is needed here */
struct MtNode* nodes; // 2^stride = 2^3 = 8
int nexthop;
};
/* Initialize binary trie node */
/* in C, struct is needed beefure MtNode */
struct MtNode* init_mtnode(){
struct MtNode *ret = malloc(sizeof(struct MtNode));
int size = (int)pow(2,STRIDE);
ret->nodes = malloc( sizeof(struct MtNode) * size );
for (int i=0; i<(int)pow(2,STRIDE); ++i)
/* ret->nodes[i] has type struct MtNode, not struct MtNode* */
/* (ret->nodes[i]) = NULL; */
{
ret->nodes[i].nodes = NULL;
ret->nodes[i].nexthop = -1;
}
ret->nexthop = -1;
return ret;
}
关于java - 具有指向 C 中结构节点的指针数组的结构节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32798447/