-1

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));
JaMiT
  • 14,422
  • 4
  • 15
  • 31
cricri
  • 1

2 Answers2

1
memcpy(A3, A1, sizeof(int) * SZ_A3)

copies the first 980 elements of A1 into A3. So A3 now contains sequential numbers up to 979.

memcpy(A3 + SZ_A3 / 2, A2, sizeof(int) * (SZ_A3 / 2));

A3 + SZ_A3 / 2 is the address of the middle element of A3, i.e. &A3[SZ_3 / 2], which is &A3[490]. So this copies the first 490 elements of A2 into the second half of A3.

So A3 now contains sequential numbers from 0 in indexes 0 through 489, and then repeats them from indexes 490 through 979.

Finally, it prints *(A3 + (SZ_A3 / 2)). This prints A3[490], which is 0.

Barmar
  • 741,623
  • 53
  • 500
  • 612
0

You haven't initialized the array A2 in descending order of its indices which you can easily do it like this:

A2[i] = SZ_A2-i-1;

i.e. A2[0] = 979, A2[1] = 978, A2[2] = 977, ... , A2[978] = 1, A2[979] = 0

Hope this will help you understand the code better.

ew88
  • 1