C从最初分配的数组中引用静态内存

C reference static memory from initially allocated array

我有软件要求不使用动态内存,最重要的是我试图用 k_dimensions、k=1(像常规数组)、k=2(二维), 等等。

在我的 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 实现中,我尝试 allocate/reference 在数组中为新节点预分配静态内存(片段):

#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];