Domanda

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
*/
È stato utile?

Soluzione

//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.

Altri suggerimenti

You're printing the wrong array, you print array twice

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]);//<-- here
printf("\n");

Of course you could just write:

int main(){

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

    memcpy(other_array, array, sizeof other_array);

    /* then print */

}

It might also be a good idea to #include <assert.h> and then:

assert(sizeof array == sizeof other_array)
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top