Initializing an array of structures in Objective-C

I read about this for a while, and I'm not sure I found a good answer.

I am trying to tune an array of 92 structures. This is a fixed length and will not change how efficient the lookup table is. I thought the best way to do this is to first allocate the memory using calloc and then load the data.

But after some reading, I see that many people allocate memory directly without calloc or malloc , like this

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

My first question is: is it better to dynamically allocate memory? I realized that this is the best solution. Especially if the data is not necessarily used all the time.

My second question is about data initialization. I read that I can initialize the structure using ... = {....}; but the compiler does not accept this.

Here is the code that I still have:

 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!" // ... 
+4
source share
3 answers

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

If you know how many elements are in the array (and this is a reasonable processor and operating system), it is always easier to define it explicitly.

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

If this is really a lookup table, and all values ​​are known at compile time, you can simply initialize it:

 struct { int a; int b; } myStructDate[92] = { {1, 2}, {3, 4}, ... {181, 182}, {183, 184} }; 
+5
source

About Question 1: The static distribution of the array should be perfect. The array will be stored in your binary data section, loaded into the virtual memory of the process and replaced by the OS if necessary, like any other part of the memory that your process uses. It will also save time when accessing data, since you do not need to allocate and initialize it.

About question 2: gcc at least doesn't like the initialization of such array elements. But you can spoof the temp variable:

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

I'm not quite sure what the standard says.

+3
source

Since this is not initialization, you need to complete the assignment

 myData[0].a = 1; myData[0].b = 2; 

You can use {} initialization when you initialize it, like this example, which also sets your array. This is a bit wasteful since you do not need the temp variable if you use the above method.

 myStruct temp = {1,2}; myStruct* myData = (myStruct *) calloc(92, sizeof(myStruct)); myData[0] = temp; 

A good rule about when to allocate memory on the heap (via malloc / calloc) is if you need to use it outside the function. Otherwise, you should probably do this on the stack (with local variables).

+2
source

Source: https://habr.com/ru/post/1402055/


All Articles