0

Here is relevant header of tree data structure:

#include <stdlib.h>
#ifndef KDTREE_H
#define KDTREE_H
#define DEFAULT_NUMBER_OF_DIMENSIONS 1
#define KD_TREE_HEAP_SIZE 100
#define MAX_DIMENSIONS 32
//References: https://www.geeksforgeeks.org/k-dimensional-tree/
//References:  https://www.cs.cmu.edu/~ckingsf/bioinfo-lectures/kdtrees.pdf
//References:https://iq.opengenus.org/k-dimensional-tree/

  /*
     * Representation of a kd tree
     */
    typedef struct tree_
    {
        struct tree *left; 
        struct tree *right; 

        float * info =  (float *) calloc (MAX_DIMENSIONS, sizeof(float));
        float distance_to_neighbor;
    } tree;

The float * info = (float *) calloc (MAX_DIMENSIONS, sizeof(float));throws compiler error:

kdtree.h:31:22: error: expected ':', ',', ';', '}' or '__attribute__' before '=' token
         float * info =  (float *) calloc (MAX_DIMENSIONS, sizeof(float));

Im able to do dynamic allocation outside of a struct but not inside of a struct? How can pre-allocate inside of a struct.

cyber101
  • 2,822
  • 14
  • 50
  • 93
  • 1
    Why do you need to do this? Just do it outside the struct or use a flexible array member. Also, [Do I cast the result of `malloc`?](https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) – ggorlen Nov 08 '19 at 01:22
  • 2
    In C, you cannot put code into a `struct` declaration; you can't have an initializer which calls `calloc`. Since `MAX_DIMENSIONS` is a constant, declare an array. `struct tree_ { ... float info[MAX_DIMENSIONS]; ...}`. Elsewhere you have to take steps to make sure it's zero initialized. `struct tree_ *p = calloc(sizeof *p)` or `struct tree_ tree = { 0 }`. – Kaz Nov 08 '19 at 01:25

1 Answers1

2

This might work, however without the calloc() or whatever:

typedef struct tree_
{
    struct tree *left; 
    struct tree *right; 

    float info[MAX_DIMENSIONS];
    float distance_to_neighbor;
} tree;
lenik
  • 23,228
  • 4
  • 34
  • 43