1

I'm trying to implement KD Tree in an app I build and the current example is something like this:

struct kd_node_t {
    int trapID;
    double x[MAX_DIM];
    struct kd_node_t *left, *right;
};

struct kd_node_t wp[] =
    {
        {1, {2, 3}}, {1, {5, 4}}, {1, {9, 6}}, {1, {4, 7}}, {1, {8, 1}}, {1, {7, 2}}
    };

What i'm trying to do is dynamically putting an array in the struct instead few like the example. Any ideas how shall I do that?

EDIT:

I realize the question should be different --> How can I initialize this specific struct from NSArray data?

Idan Moshe
  • 1,675
  • 4
  • 28
  • 65
  • Why do you want to use instances of `NSArray`? C has the ability to put arrays of dynamic size into a structure. There are at least two approaches. – Amin Negm-Awad Jan 05 '14 at 09:32

2 Answers2

0

You can just:

struct kd_node_t {
    NSArray *myArray
};

kd_node_t myStruct;
myStruct.myArray = [newArray retain];

It should work.

Avi Tsadok
  • 1,843
  • 13
  • 19
  • 2
    Just note that this will not compile if you use Automatic Reference Counting (ARC). – Martin R Jan 05 '14 at 07:55
  • http://stackoverflow.com/questions/11857117/unsafe-unretained-nsstring-struct-var This can help for ARC based applications. – Avi Tsadok Jan 05 '14 at 08:01
0

If you are using ARC then defining a struct with an NSArray * field is non-trivial, but can be done if you are prepared to use __unsafe_unretained references.

It is not clear from your question that you need to use a struct for some reason. If you are doing it to obtain a "lightweight" structure then a methodless-class can be used:

@interface KD_Node : NSObject
{
   int trapID;
   NSArray *x;
   KD_Node *left, *right;
}
@end

@implementation KD_Node
@end

Apart from allocation, where a call to malloc() (or friend) is replaced by [KD_Node new], using a KD_Node * is just like using a struct kd_node_t * - the fields (instance variables) are referenced using the -> operator. There is a slight storage overhead compared to a straight struct, but you get to use your NSArray * without issue. (Of course you can add properties and/or methods later if you wish as well.)

HTH

CRD
  • 52,522
  • 5
  • 70
  • 86