Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array equal another array

Tags:

arrays

c

pointers

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;
}
like image 599
user978281 Avatar asked Feb 13 '12 15:02

user978281


People also ask

How do you make an array equal another array?

Ensure that the two arrays have the same rank (number of dimensions) and compatible element data types. Use a standard assignment statement to assign the source array to the destination array. Do not follow either array name with parentheses.

Can you make one array equal to another?

As mentioned above, arrays in Java can be set equal to another array using several ways. Here are a few ways: Create an array with the same length as the previous and copy every element. Using the System.

How do you check if an array is equal to another?

The Arrays. equals() method checks the equality of the two arrays in terms of size, data, and order of elements. This method will accept the two arrays which need to be compared, and it returns the boolean result true if both the arrays are equal and false if the arrays are not equal.


1 Answers

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.

like image 116
Jason Avatar answered Oct 17 '22 20:10

Jason