简体   繁体   中英

difference between array and pointer to array

Hello Stack overflow community,

Since embedded systems are resources limited, we have to take care of the memory allocation.

So, my question is about this topic (how to save memory?)

Suppose we have this piece of code:

extern float externArray[2500];
float testArray[2500];
void fillArray()
{
for (unsigned i = 0; i < sizeof(testArray) / sizeof(float); i++)
  testArray[i] = externArray[i];
}

If you're wondering why I'm copying the externArray into the testArray, my application obliges me to do that (because I will pass externArray to a function that will modify its values). If you have a better approach to do this, your feedbacks are welcome.

Now I have done this:

extern float externArray[2500];
float *testArray;
void fillArray()
{
testArray = (float*) malloc(2500 * sizeof(float));
for (unsigned i = 0; i < sizeof(externArray) / sizeof(float); i++) //here I have to change size of testArray to size of externArray because it's no more longer allocated on the stack
  testArray[i] = externArray[i];
}

So I want to know if the second will be more optimized in terms of memory since I'm using a pointer to an array?

Is worth it to use more heap (I mean more pointers to arrays than arrays)?

Thank you

The dynamic memory allocation will be marginally less efficient in terms of memory usage because of the alignment and heap-management meta-data required to manage allocation and deallocation.

However a more significant issue is that of the non deterministic nature of dynamic allocation. Allocation will take variable time, and may fail. Statically allocated arrays take no time and are guaranteed to be available.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM