Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the easiest way to create an array of structs?

Tags:

What's the easiest way to create an array of structs in Cocoa?

like image 789
Steph Thirion Avatar asked Dec 25 '08 20:12

Steph Thirion


People also ask

How do you create a struct array?

Create an Array of struct Using the malloc() Function in C The memory can be allocated using the malloc() function for an array of struct . This is called dynamic memory allocation. The malloc() (memory allocation) function is used to dynamically allocate a single block of memory with the specified size.

How do you create an array of structs in Objective C?

@interface Foo : NSObject { NSString *name; NSArray *books; } @end A->name = @"Clancy, Thomas"; A->books = [[NSArray alloc] initWithObjects:@"Book 1" @"Book2",nil]; self. authors = [[NSArray alloc] initWithObjects:A, nil];

Can you store a struct in an array?

A structure may contain elements of different data types – int, char, float, double, etc. It may also contain an array as its member. Such an array is called an array within a structure. An array within a structure is a member of the structure and can be accessed just as we access other elements of the structure.


2 Answers

If you want to use an NSArray you'll need to box up your structs. You can use the NSValue class to encode them.

Something like this to encode:

struct foo {
    int bar;
};

struct foo foobar;
foobar.bar = 3;
NSValue *boxedFoobar = [NSValue valueWithBytes:&foobar objCType:@encode(struct foo)];

And then to get it back out:

struct foo newFoobar;

if (strcmp([boxedFoobar objCType], @encode(struct foo)) == 0)
    [boxedFoobar getValue:&newFoobar];
like image 144
Ashley Clark Avatar answered Oct 28 '22 16:10

Ashley Clark


Or dynamically allocating:

struct foo {
    int bar;
};

int main (int argc, const char * argv[]) {
    struct foo *foobar = malloc(sizeof(struct foo) * 3);
    foobar[0].bar = 7; // or foobar->bar = 7;

    free(foobar);
}
like image 41
Georg Schölly Avatar answered Oct 28 '22 15:10

Georg Schölly