Search code examples
arrayscperformancecopystack

Fastest way to copy various arrays into a single larger array in C without dynamic memory allocation


I was wondering what would be the fastest (or a very fast) way to combine two different arrays into one larger array. As a toy example, let us say I want to combine initialized arrays int smallArray0[3] and int smallArray1[2].

I could instead just use, for example, a pointer via mallocs, memcpys and frees, but I am under the impression (correct me if I am wrong) that it is faster to keep everything in the stack (for smaller amounts of data). For this reason, let us not use dynamic allocation.

If I want to do an actual duplicate of the data, I can only think of declaring an int biggerArray[5] and using a for/while loop to populate it like so:

for (int i = 0; i < 3; i++)
    biggerArray[i] = smallerArray0[i];
for (i = 3; i < 5; i++)
    biggerArray[i] = smallerArray1[i - 3];

Is there be a way of not having to actually copy the data and having some sort of pointer that sequentially points to all elements of smallArray0 and finally to smallArray1? If this is possible, would this be faster?

I hope that makes sense, and if not I am happy to clarify.


Solution

  • Thanks all for the great input, I certainly learned a good amount about C and the underlying structures of arrays. It seems like memcpy (with or without offsets) seems to be the fastest way, especially as, at least the glibc implementation of memcpy, can copy word-by-word rather than byte-by-byte and, as the comment by Ludin mentioned, using for loops for copying arrays frequently produce the same machine code as using memcpy (depends on the compiler of course).