Search code examples
carrayscopying

Copying of array leads to 0's?


I am learning C and one of my functions (not shown here) depends on two arrays being the same. I have one array and am trying to generate a copy but what happens is that both arrays turn out to be full of 0's after the copy. I have no idea how this happens.. Can anybody help explain why this happens and offer a solution on how to do it right?

#include <stdio.h>

int main(){

    int array[5]={3,2,7,4,8};
    int other_array[5]={0,0,0,0,0};

    for (int i=0; i<5; i++) array[i]=other_array[i];    //Copies array into other_array

    printf("array is:\n");
    for (int j=0; j<5; j++) printf("%d", array[j]);
    printf("\nother_array is:\n");
    for (int i=0; i<5; i++) printf("%d", other_array[i]);
    printf("\n");

    return 0;
}

/*
When run this yields
**********************
array is:
00000
other_array is:
00000
*/

Solution

  • //Copies array into other_array
    for (int i=0; i<5; i++) array[i]=other_array[i];    
    

    Try:

    other_array[i] = array[i];
    

    The assignment operator assigns the value of the right operand into the object in the left operand. And not the opposite.

    Also, as said in other answers:

    printf("\nother_array is:\n");
    for (int i=0; i<5; i++) printf("%d", array[i]);
    

    Your are printing array and not other_array.