gpt4 book ai didi

c - 为什么根节点值无效?

转载 作者:行者123 更新时间:2023-12-03 03:30:14 26 4
gpt4 key购买 nike

我想创建一棵回归树。为什么生成树后无法从根节点获取有效值?

/* 
* File: main.c
* Author: C-AP
*
* Created on September 9, 2011, 8:06 PM
*/
#include <stdio.h>
#include <stdlib.h>

typedef struct regnode {
int setsize;
int* set;
int tokenpos;
int nextsize;
struct regnode** next;
} regnode;

/*
* print array
*/
void printliniar2(int dim, int* mat, char* label) {
int i;
printf("\n%s\n", label);
for (i = 0; i < dim; i++)
printf(" %d ,", mat[i]);
printf("\n");
}

/*
* copies array source to array destination
*/
void copyToInt(int dim, int* Source, int* Destination) {
int i;
for (i = 0; i < dim; i++)
Destination[i] = Source[i];
}

void getReducedSet(int dim, int* set, int delpos, int* newset){
int i,j=0;
for(i=0;i<delpos;i++,j++)
newset[j] = set[i];
for(i=delpos+1;i<dim;i++,j++)
newset[j] = set[i];

}

void genTree(int setsize, int* set, int tokenpos, regnode* node){

printf("\n**********************************\n");

//allocate memory for node variable
node = (regnode*)malloc(sizeof(regnode));

//insert set dimension
node->setsize = setsize;
printf("node setsize : %d",node->setsize);

//allocate set space
node->set = calloc(node->setsize,sizeof(int));

//insert set into node
copyToInt(setsize,set,node->set);
printliniar2(node->setsize,node->set,"node set (copy)");

//insert token position
node->tokenpos = tokenpos;
printf("\nnode tokenpos : %d\n",node->tokenpos);

//insert number of next nodes
node->nextsize = setsize - 1 - tokenpos;
printf("\nnode nextsize : %d\n",node->nextsize);

//allocate memory for next nodes
node->next = malloc(node->nextsize*sizeof(regnode*));

//create children nodes
int i;
for(i=0;i<node->nextsize;i++){
//create next node
regnode* next;

//get reduced set for child node
int* newset = calloc(setsize-1,sizeof(int));
getReducedSet(setsize,set,tokenpos+i,newset);

//keep reference to next node
node->next[i] = next;

//recursively call genTree
genTree(setsize-1,newset,tokenpos+i,next);
}
}

/*
void exploreTree(regnode* root){
printf("\n**********************************\n");
printf("\nnode setsize : %d\n",root->setsize);
printliniar2(root->setsize,root->set,"set");
printf("\nNumber of next nodes : %d\n",root->nextsize);
int i;
for(i=0;i<root->nextsize;i++)
exploreTree(root->next[i]);
}
*/

/*
*
*/
int main(int argc, char** argv) {
int dim = 5;
int set[] = {1,2,3,4,5};
int tokenpos=0;
regnode* root;

genTree(dim,set,tokenpos,root);
//exploreTree(root);

printf("\nSet dimension : %d\n",root->setsize);
printliniar2(root->setsize,root->set,"set");
printf("\nNumber of next nodes : %d\n",root->nextsize);

return (EXIT_SUCCESS);
}

最佳答案

root 按值传递,genTree 永远不会返回创建的节点。

关于c - 为什么根节点值无效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7372088/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com