I have 3 arrays A1, A2, A3 defined in C program, with size of 1500, 980, 980 respectively. A1 initialized by the indices of elements in ascending order, A2 - by the indices too, but in descending order. At the moment after initialization of A1 and A2 these actions are performed:
int* A3 = malloc(sizeof(int) * SZ_A3);
memcpy(A3, A1, sizeof(int) * SZ_A3);
memcpy(A3 + SZ_A3 / 2, A2, sizeof(int) * (SZ_A3 / 2));
printf("%i", *(A3 + (SZ_A3 / 2)));
There are definitions of SZ_A#:
#define SZ_A1 1500
#define SZ_A2 980
#define SZ_A3 980
Which value will be in the standard output stream?
Answer: 979
I would like to know why the answer is 979. My code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SZ_A1 1500
#define SZ_A2 980
#define SZ_A3 980
int main(void) {
int i, A1[SZ_A1], A2[SZ_A2];
// inicializo el array A1 en orden ascendente por sus indices. from i = 0 to i = SZ_A1-1
for (i = 0; i < SZ_A1; i++)
A1[i] = i;
// inicializo el array A2 en orden descendente por sus indices. from i = SZ_A2-1 to i = 0
for (i = SZ_A2 - 1; i >= 0; i--)
A2[i] = i;
int* A3 = malloc(sizeof(int) * SZ_A3);
memcpy(A3, A1, sizeof(int) * SZ_A3);
memcpy(A3 + SZ_A3 / 2, A2, sizeof(int) * (SZ_A3 / 2));
printf("%i", *(A3 + (SZ_A3 / 2)));
return 0;
}
I do not understand the lines
memcpy(A3, A1, sizeof(int) * SZ_A3)
What is the value of A3?. With memcpy, sizeof(int) * SZ_A3
bytes to be copied, then from memory area A1 to memory area A3?.
memcpy(A3 + SZ_A3 / 2 + 1, A2, sizeof(int) * (SZ_A3 / 2));