This is a stripped down version of my program. I need to pass a pointer to pointers of structs to a function, modify the structs within the function, and have those changes persist. The function declaration must stay the same.
Currently I can modify the data within the function, but once returned to main, no changes were made.
Thank you for your help.
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;
}
}
You have a pointer typing problem. I'm surprised that it even compiles since &HuffmanNodes
is of type node***
.
Try this:
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;
}
}
You also have some naming mismatches (which I fixed), I hope those are just typos from stripping down the program.
EDIT: Alternative Method
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;
}
}
Try this:
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;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.