java - 具有指向 C 中结构节点的指针数组的结构节点

标签 java c struct

我正在用 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/

相关文章:

将 GCC 的 __builtin_ia32_pshufd 和 __v4si 模式转换为可移植内在模式?

c - 不存储数据的结构指针的全局数组

C++ 从结构数组中得到错误的值

java - GWT XML 模式

java - 如何限制为 double 打印的小数位数?

java - 查找 WebElements,最佳实践

java - Bean Validation 将 Object RequestParam 转换为 @RequestBody

c++ - 将带符号的 Int 转换为带空格的十六进制字符串

c - 在 C 中访问二维数组的元素

c - 64 位系统结构大小