1

I am trying to copy elements from two arrays into a third.
I can't understand why it doesn't work.
I made sure that the two arrays are filled properly, but for some reason, the actual copying doesn't work- when I print the elements of the arr3, I get some random numbers.

#include <stdio.h>

int main()
{
    int arr1[10], arr2[10], arr3[20];
    int i, n;


    printf("Enter a number of elements to be stored in each array (up to 10): ");
    scanf("%d", &n);
    printf("Enter the %d elements to the first array:\n", n);
    for (i = 0; i < n; i++)
    {
        printf("Element %d: ", i + 1);
        scanf("%d", &arr1[i]);
    }
    printf("Enter the %d elements to the second array:\n", n);
    for (i = 0; i < n; i++)
    {
        printf("Element %d: ", i + 1);
        scanf("%d", &arr2[i]);
    }
/*
// A test to make sure first 2 array are filled by the user- works

    for(i = 0; i < n; i++)
        printf("%d  ", arr1[i]);
    for(i = 0; i < n; i++)
        printf("%d  ", arr2[i]);

*/
    // something wrong here, the elements are not coppied to the third array
    for(i = 0; i < n; i++);
            arr3[i] = arr1[i];
    for(i = n; i < 2 * n; i++)
        arr3[i] = arr2[i];


    for(i = 0; i < 2 * n; i++)
        printf("%d\n", arr3[i]);

    return(0);
}
3
  • arr3[i]=arr2[i]; : The subscript of arr2 should start from 0. Commented Apr 18, 2017 at 14:29
  • #include <string.h> memcpy(arr3, arr1, n * sizeof(*arr1)); memcpy(arr3 + n, arr2, n * sizeof(*arr2)); Commented Apr 18, 2017 at 14:32
  • 1
    Watch out for an extra (incorrect) semicolon! Commented Apr 18, 2017 at 14:37

2 Answers 2

3

You're reading past the end of arr2, try this;

for (i = 0; i < n; i++)
        arr3[i] = arr1[i];
for (i = 0; i < n; i++)
    arr3[n+i] = arr2[i];
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. I understand why your code works, I don't understand why my doesn't. Lets say n=3. when I copy from arr2 I start from arr3[3] and end with arr3[5]. what is it wrong?
arr1 and arr2 have elements 0, 1, and 2. When n is 3. If you first copy arr1[0..2] to arr3[0..2] then you try to copy arr2[3..5] to arr3[3..5] but arr2 doesn't have data there. Do you understand?
I do now. Thanks. Can't find where you mark the question as resolved..
-1

That's because your code is reading arr2[10],arr2[11] ..... arr2[19] (if n=10 ), all these values do not exist because arr2 only has 10 values. you can use this.

for (i=0; i<n; i++)
arr3[n+i]=arr2[i];

or

for (i=n; i<n*2; i++)
arr3[i]=arr2[i-n];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.