#include <string.h>
#define ARRAY_LENGTH 4
// insert your code above here.. and as the other answer says you should
// always check malloc's return value to make sure it succeeded before
// continuing or you will seg fault. If it fails, you should gracefully
// handle the error
memcpy(b, a, sizeof(int) * ARRAY_LENGTH); // copies sizeof(int)*ARRAY_LENGTH bytes
// from the memory space pointed to by a
// to the memory space pointed to by b
free(a); // returns the memory pointed to by a to the heap
More information about memcpy can be found here. It's a highly optimized function for copying memory. If you only have 4 values, I doubt you'll see much performance difference between your own loop, memcpy, or simply manually-assigning (unrolling the loop) each value,, unless you're running this many thousands or millions of times.
And just a side note, as a general rule of thumb, you want to use malloc as sparingly as possible. The only times you should use it are if you don't know how much memory you'll need until runtime, or if you want the scope of the memory to persist outside of the function. Incorrectly managing memory is the source of many, many bugs that can be difficult to track down in large programs since they don't always manifest themselves at the same time in the same place the same way. Here, you don't show enough code for me to know exactly what you're doing. But you do know the size of the array ahead of time (4 ints), so unless you need these arrays outside of the function, just go ahead and put them in localized scope (on the stack in most systems):
int a[4];
int b[4];
// perform assignment to a
// perform copy to b
// do work on data
// ....
// now when the function ends, these arrays will automatically get destroyed, saving you the trouble
I'll just take you at your word that you have a good reason for copying the a array, as that's not evident from your code.
Finally, this was a dupe and neither of us should've answered it :)
How to copy one integer array to another
int *a = malloc(4 * sizeof(*a));— while both versions are correct, writing it this way means you’re a little less likely to make a mistake.