'Copying elements of an array in C having unexpected results [duplicate]

I am trying to copy elements of an array using a simple copy function outside of main. My code is as follows:

int* copy(int* nums){
    int size = sizeof(nums) / sizeof(nums[0]); // len of array
    int *arr = (int*)malloc(size * sizeof(int)); // dynamic allocation of array mem
    *arr = *nums; // copy operation
    return arr; // return copied arr
}

int main(){
    int nums[] = {1,2}; 
    int array[2];
    *array = *copy(nums); // operation in question
    printf("[%d, %d]", array[0], array[1]);
}

My output:

[1, 0]

It seems like the copy function is returning only the first element in my array. Can someone explain to me why this is happening?



Solution 1:[1]

  1. *nums returns the first element of nums
  2. *arr = whatever; assigns whatever to the first element of arr

Thus, *arr = *nums; is a "copy one element operation". Same thing with *array = *copy(nums);, by the way.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ForceBru