gpt4 book ai didi

在树中创建节点

转载 作者:太空宇宙 更新时间:2023-11-04 00:47:55 25 4
gpt4 key购买 nike

我在使用这段代码时遇到问题:

#include<stdlib.h>
#include<stdio.h>

struct quadtree
{
char colour;
int x_coordinate;
int y_coordinate;
int size;
struct quadtree *NW, *NE, *SE, *SW, *p;
};

static struct quadtree *p = NULL;

int size;
int i;
int pixels;
int width;
int black_pixels;

void insert(struct quadtree **p , char colour , int size , int x_coordinate , int y_coordinate)
{
struct quadtree *new;
new = (struct quadtree *) malloc ( sizeof(struct quadtree) );
new->NW = new->NE = new->SE = new->SW = NULL;
new->colour = colour;
new->size = size;
new->x_coordinate = x_coordinate;
new->y_coordinate = y_coordinate;
*p = new;
/* printf("%c\n" , p->colour); */
printf("%c\n" , new->colour);
return;
}


void colour_test(int x[] , int y[] , int size , int x_coordinate , int y_coordinate , struct quadtree *p)
{
pixels = 0;
for (i = 0 ; i < black_pixels ; i++)
if (x[i] >= x_coordinate && x[i] < (size + x_coordinate) && y[i] <= y_coordinate && y[i] > (y_coordinate - size))
pixels++;

if (pixels == 0)
{
insert(&p , 'W' , size , x_coordinate , y_coordinate);
/* printf("Node has coordinates (%d,%d) and a size of %d\n" , x_coordinate , y_coordinate , size); */
}
else if (pixels == size*size)
{
insert(&p , 'B' , size , x_coordinate , y_coordinate);
/* printf("Node has coordinates (%d,%d) and a size of %d\n" , x_coordinate , y_coordinate , size); */
}
else
{
insert(&p , 'G' , size , x_coordinate , y_coordinate);
/* printf("Node has coordinates (%d,%d) and a size of %d\n" , x_coordinate , y_coordinate , size); */
colour_test(x , y , size/2 , x_coordinate , (y_coordinate - (size/2)) , p->NW);
colour_test(x , y , size/2 , (x_coordinate + (size/2)) , (y_coordinate - (size/2)) , p->NE);
colour_test(x , y , size/2 , (x_coordinate + (size/2)) , y_coordinate , p->SE);
colour_test(x , y , size/2 , x_coordinate , y_coordinate , p->SW);
}
}

int main()
{
scanf("%d" , &width);
scanf("%d" , &black_pixels);

int x[black_pixels];
int y[black_pixels];
for (i = 0 ; i < black_pixels ; i++)
scanf("%d%*[ ]%d" , &x[i] , &y[i]);
/*
printf("Image width = %d\n" , width );
printf("Total black pixels = %d\n" , black_pixels);
for (i = 0 ; i < black_pixels ; i++)
printf("%d %d\n" , x[i] , y[i]);
*/
size = width;
colour_test(x , y , size , width - size , (width - 1) , p);

return 0;
}

它几乎按预期工作,在相同颜色的象限中处理图像。但是我在树中创建节点时遇到问题。我试图创建一个指向新节点的指针,然后用数据加载该新节点,然后将新节点加入到它的父节点。

一旦完成,我试图打印出节点,但我收到一条错误消息说

request for member ‘colour’ in something not a structure or union

但是当我删除该行时,我能够在新节点中正常打印数据。我怎样才能确保节点确实加入了树?我是否需要创建结构变体来执行此操作:我之前有一段代码用于二叉树,我一直在尝试根据它进行调整。

最佳答案

这是因为您的代码中有一个双指针,您必须取消引用才能使该行工作:printf("%c\n", p->colour);

也就是例如:

printf("%c\n" , (*p)->colour);

另外,请注意您有一个全局静态变量也名为 p:static struct quadtree *p = NULL;。您可以更改全局变量的名称以避免歧义。

关于在树中创建节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30034925/

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