Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Weird behavior with C array

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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;
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading