I have a loop that goes something like this, where arrayfunction sets all array values and compute_with_both_arrays computes a number based on both these arrays.
They way i did it below does not work for array1 = array2. Is there a way i can do this without running the arrayfuncion twice in each loop?
float sum = 0;
float array1[10];
arrayfunction(0, array1);
for(i=1; i<10; i++) {
float array2[10]
arrayfunction(1, array2);
float s;
s = compute_with_both_arrays(array1, array2);
sum = sum + s;
array1 = array2;
}
You have to manually copy the memory from one array to another using a function like
memcpy.So for instance:
Keep in mind that we can use the
sizeofoperator onarray1because it’s an explicit array allocated on the stack. As a commenter noted, we pass the size of the destination to avoid a buffer over-run. Note that the same technique could be done for a statically allocated array as well, but you cannot use it on an array dynamically allocated on the heap usingmalloc, or with some pointer-to-an-array … in those situations, you must explicitly pass the size of the array in bytes as the third argument.Finally, you’ll want to use
memcpyover afor-loop because the function is typically optimized for copying blocks of memory using instructions at the machine-code level that will far out-strip the efficiency of a for-loop, even with compiler optimizations turned on.