user978281
user978281

Reputation: 477

Array equal another array

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;
}

Upvotes: 9

Views: 55900

Answers (1)

Jason
Jason

Reputation: 32510

You have to manually copy the memory from one array to another using a function like memcpy.

So for instance:

memcpy(array1, array2, sizeof(array1));

Keep in mind that we can use the sizeof operator on array1 because 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 using malloc, 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 memcpy over a for-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.

Upvotes: 15

Related Questions