Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialising an array of structs in Objective-C

I've been reading about this for a while and I'm not sure I have found a good answer.

I'm trying to setup an array of 92 structs. It's a fixed length and will not change as it's effectively a lookup table. I thought that the best way to do this was to first allocate the memory with calloc and then load the data.

But after some reading I see a lot of people allocating the memory directly without calloc or malloc like this

 myStruct myData[92] = { {1,2}, {3,4}, ....};

My first question is whether it is better to dynamically allocate the memory? My understanding was that this was a better solution. Especially if the data is not necessarily going to be used all the time.

My second question is in regards to initialising the data. I had read that I can initialise a struct using ... = {....}; but the compiler is not accepting that.

Here is the code I have so far:

typedef struct {
    int a;
    int b;
} myStruct;

@implementation MyClass

    static myStruct *myData;

    -(id) init {
         // ...

         myData = (myStruct *) calloc(92, sizeof(myStruct));
         myData[0] = {1,2}; // <=== Error ! Compiler says "Expected expression!"

         // ...
like image 495
drekka Avatar asked Dec 27 '22 04:12

drekka


2 Answers

Your code looks like Objective-C, is that correct?

If you know how many elements are in an array (and it is a sane processor and operating system), it is always simpler to explicitly define it.

Whenever you dynamically allocate an array, you need to protect against something going wrong, which makes the code harder to understand.

If it is really a lookup table, and all of the values are known at compile time, you can just initialise it:

struct {
    int a;
    int b;
} myStructDate[92] = { {1, 2}, {3, 4}, ... {181, 182}, {183, 184} };
like image 135
gbulmer Avatar answered Jan 17 '23 17:01

gbulmer


About question 1: statically allocating the array should be just fine. The array will be stored in your binary's data section, will be loaded into the process's virtual memory, and swaped out by the OS if necessary, just like any other piece of memory your process is using. It will also save time when accessing the data, since you don't need to allocate and initialize it.

About question 2: gcc at least doesn't like initializing array elements like that. But you can cheat using a temp variable:

myStruct s = {1,2};
myData[0] = s;

I'm not really sure what the standard says regarding this.

like image 34
vanza Avatar answered Jan 17 '23 19:01

vanza