C ссылка на статическую память из первоначально выделенного массива - PullRequest
0 голосов
/ 02 ноября 2019

У меня есть требование к программному обеспечению не использовать динамическую память, кроме того, я пытался создать kd-дерево с k_dimensions, k = 1 (как обычный массив), k = 2 (2-мерное) и так далее.

В моем заголовке kd_tree.h у меня есть представление дерева (фрагмент):

 /*
     * 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];?

Спасибо

1 Ответ

0 голосов
/ 02 ноября 2019

Просто быстрый квест. Похоже, вы хотите, чтобы ваша 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];
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...