I have the following C code:
int array_len(int *a) {
int i;
for(i = 0; i < ARRAY_SIZE && a[i] != TERMINATOR; i++);
return i;
}
void jumbleArrays(int *a1, int *a2)
{
int a1_len = array_len(a1);
a2 = a1;
a2[a1_len] = 42;
if(a1_len <= ARRAY_SIZE)
a2[a1_len+1] = TERMINATOR;
a1 = malloc(sizeof(int) * ARRAY_SIZE);
a1[0] = 41;
a1[1] = TERMINATOR;
}
int main()
{
int a1[ARRAY_SIZE];
int a2[ARRAY_SIZE];
a1[0] = 10;
a1[1] = 4;
a1[2] = TERMINATOR;
a2[0] = 7;
a2[1] = 9;
a2[2] = 11;
a2[3] = TERMINATOR;
jumbleArrays(a1, a2);
printf("Contents of a1: ");
for(int i = 0; i < ARRAY_SIZE && a1[i] != TERMINATOR; i++) {
printf("%d ", a1[i]);
}
printf("\n");
printf("Contents of a2: ");
for(int i = 0; i < ARRAY_SIZE && a2[i] != TERMINATOR; i++) {
printf("%d ", a2[i]);
}
printf("\n");
return 0;
}
Why when the program is ran why isn't the output the following?
Contents of a1: 41
Contents of a2: 10 4 42
But instead it is Contents of a1: 10 4 42
Contents of a2: 7 9 11
The JumbleArrays is taking a pointer (nothing but an address) and then makes changes to the existing array a1. It then creates a new array on the heap whose base address will be stored in a1, but it seems like after the jumbleArrays() method returns that address is no longer stored in a1? Overall, I'm not sure as to why a1 and a2 refer to their older arrays when clearly they store different addresses in jumbleArrays.