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;
}
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With