我的软件要求不使用动态内存,除此之外,我尝试使用 k_dimensions、k=1(如常规数组)、k=2(二维)等制作 kd 树。
在我的 kd_tree.h header 中,我有一个树的表示(片段):
/*
* Representation of a kd tree
*/
typedef struct tree_
{
struct tree *left;
struct tree *right;
//DEFAULT_NUMBER_OF_DIMENSIONS
float * info;
float distance_to_neighbor;
} tree;
在我的 kd_tree.c 实现中,我尝试为新节点分配/引用数组中预先分配的静态内存(片段):
#include "kdtree.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <float.h>
static int current_number_of_kd_tree_nodes=0;
static int current_number_of_data_points=0;
static int k_dimensions=0;
//pre-allocated tree nodes array
static tree tree_space [100];
//pre-allocated data_point array
//TODO: later make sure data_points is at least sizeof(t_memory)/sizeof(tree) * k_dimensions
static float data_points_space [1000];
/*=============================================================================
Function new_node
Description: given data create a tree
==========================================================*/
tree *
new_node (tree * root, float data[], int k_dimensions)
{
if (NULL == root)
{
//dynamic memory allocation is NOT allowed, malloc(sizeof(tree));
root = &tree_space [current_number_of_kd_tree_nodes];
//dynamic memory allocation is NOT allowed, root->info = malloc(k_dimensions * sizeof(float));
for (int i=0;i<k_dimensions;i++)
{
//TODO: later deal with fragmentation when you remove nodes
//HOW DO I set address of the data_points array to root->info pointer
//info+i represents info[i]
root->info = &data_points_space[current_number_of_data_points+i];
}
//too keep track of what range of the
current_number_of_data_points = current_number_of_data_points + k_dimensions;
//initialize array
if (!root)
{
printf ("insert_tree(),Out of Memory\n");
}
//set max dimensions
set_k_dimensions (k_dimensions);
root->left = NULL;
root->right = NULL;
for (int i = 0; i < get_k_dimensions (); i++)
{
root->info[i] = data[i];
}
current_number_of_kd_tree_nodes++;
}
return root;
}
我现在崩溃了。这是引用 data_points 数组 root->info = &data_points_space[current_number_of_data_points+i];
的正确方法吗?
谢谢
最佳答案
只是一个快速任务。看起来您希望将“root->info”用作数据点数组。在本例中,将其设置为指向数组第一个元素的指针。
即替换循环:
for (int i=0;i<k_dimensions;i++)
{
//TODO: later deal with fragmentation when you remove nodes
//HOW DO I set address of the data_points array to root->info pointer
//info+i represents info[i]
root->info = &data_points_space[current_number_of_data_points+i];
}
通过单个作业:
root->info = &data_points_space[current_number_of_data_points];
关于C 从最初分配的数组中引用静态内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58668392/