c - 指向传递给函数的结构的指针

标签 c pointers persistence struct

这是我的程序的精简版本。我需要将指向结构指针的指针传递给函数,修改函数内的结构,并使这些更改持续存在。函数声明必须保持不变。

目前我可以在函数内修改数据,但是一旦返回main,就没有进行任何更改。

感谢您的帮助。

int main()
{
    struct node** HuffmanNodes;
    read_Huffman_encoded_data(&HuffmanNodes);
}

void read_Huffman_encoded_data(**HuffmanNodes)
{
    Huffman_node = (node**)malloc(sizeof(node*)*(*number_of_nodes));

    int index;
    for(index=0; index<*number_of_nodes;index++)
    {
        Huffman_node[index] = (node*)malloc(sizeof(node));
        Huffman_node[index]->first_value=1;
        Huffman_node[index]->second_value=2;
    }
}

最佳答案

您遇到了指针输入问题。我很惊讶它甚至可以编译,因为 &HuffmanNodes 的类型是 node***

试试这个:

void read_Huffman_encoded_data(struct node ***HuffmanNodes)
{
    *Huffman_nodes = (node**)malloc(sizeof(node*)*(*number_of_nodes));

    int index;
    for(index=0; index<*number_of_nodes;index++)
    {
        (*Huffman_nodes)[index] = (node*)malloc(sizeof(node));
        (*Huffman_nodes)[index]->first_value=1;
        (*Huffman_nodes)[index]->second_value=2;
    }
}

您还存在一些命名不匹配的情况(我已修复),我希望这些只是剥离程序时出现的拼写错误。

编辑:替代方法

int main()
{
    struct node** HuffmanNodes = (node*)malloc(sizeof(node) * (*number_of_nodes));
    read_Huffman_encoded_data(HHuffmanNodes);
}

void read_Huffman_encoded_data(struct node **HuffmanNodes)
{
    int index;
    for(index=0; index<*number_of_nodes;index++)
    {
        Huffman_nodes[index] = (node*)malloc(sizeof(node));
        Huffman_nodes[index]->first_value=1;
        Huffman_nodes[index]->second_value=2;
    }
}

关于c - 指向传递给函数的结构的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7898817/

相关文章:

c++ - wininet 或 winhttp,这是 POST 请求的首选

c - 写入 .txt 文件?

c - 并行化函数,内核内部的内核是可能的吗?海湾合作委员会

c - 将图像转为灰度图

c++ - 将读取预编译的着色器文件发送到 ID3DBlob

c++ - 什么是 char* const argv[]?

cgo 与使用线程本地存储的 C 库交互

java - JDO中无法删除照片

persistence - 通读如何在 ignite 中工作

ruby-on-rails - rails : How do I call `self.save` in my model and have it persist in the database?