I have two arrays A
and B
both with the same elements { 1, 2, 3, 4 }
but after doing A[B[i]] = A[i] 1
array B
is getting populated with different number but in reality it should be unchanged.
#include <stdio.h>
void arrayPrint(int *arr, int size) {
for (int i = 0; i < size; i ) {
printf("%d ", arr[i]);
}
printf("\n");
}
int main() {
int A[4] = { 1, 2, 3, 4 };
int B[4] = { 1, 2, 3, 4 };
int n = 3;
printf("Before \n");
printf("Array A \n");
arrayPrint(A, 4);
printf("Array B \n");
arrayPrint(B, 4);
for (int i = 0; i <= n; i ) {
if (A[i] == B[i]) {
A[B[i]] = A[i] 1;
}
}
printf("\nAfter \n");
printf("Array A \n");
arrayPrint(A, 4);
printf("Array B \n");
arrayPrint(B, 4);
return 0;
}
Output is:
Before
Array A
1 2 3 4
Array B
1 2 3 4
After
Array A
1 2 3 4
Array B
5 2 3 4
but it should be:
Before
Array A
1 2 3 4
Array B
1 2 3 4
After
Array A
1 2 3 4
Array B
1 2 3 4
CodePudding user response:
For B[i]
equal to 4
the expression A[B[i]]
access memory beyond the array A
because the valid range of indices for the array A
is [0, 3]
.
So it seems the compiler placed the array B
at once after the array A
and the first element of the array B
was changed in this statement
A[B[i]] = A[i] 1;
for i
equal to 3.
Instead of your for loop
for (int i = 0; i <= n; i ) {
if (A[i] == B[i]) {
A[B[i]] = A[i] 1;
}
}
you could write for example
for (int i = 0; i <= n; i ) {
if ( i != 3 && A[i] == B[i]) {
A[B[i]] = A[i] 1;
}
}
Or more precisely
const size_t N = sizeof( A ) / sizeof( *A );
for (int i = 0; i <= n; i ) {
if ( i != N - 1 && A[i] == B[i]) {
A[B[i]] = A[i] 1;
}
}
CodePudding user response:
In last iteration of the for
loop, i
has the value 3
, so A[B[i]] = A[i] 1;
evaluates as A[4] = A[3] 1;
.
Storing anything into A[4]
has undefined behavior. What you observe is consistent with the array B
being placed in memory immediately after array A
but this is by no means guaranteed by the C Standard. The behavior is just undefined and anything can happen.