0

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?

  • `sizeof()` is not used to determine the length of pointer array, it is only used to stack arrays eg, `int arr[3];`. So, add a parameter for length of the array. Also use `for loop` or `memcpy` for copying the data – Darth-CodeX Feb 12 '22 at 09:33

1 Answers1

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

ForceBru
  • 43,482
  • 10
  • 63
  • 98
  • `array[0]` = `*(array + 0)` = `*(array)` = `*array` So `*arr = *nums`; is the same as `arr[0] = nums[0];`. – David Schwartz Feb 12 '22 at 08:27
  • Thanks for that, made things clear as to what's happening. So, is there an efficient/easier way of copying elements over to another array without manually dereferencing the values I want copy? Thanks for humoring my newbie question. – Gianni Crivello Feb 12 '22 at 08:34
  • @GianniCrivello, 1) `sizeof(nums) == sizeof(int *) == 8` (or maybe 4) since `nums` is a pointer, so you aren't actually calculating the size of the array; 2) If you had the correct size, you could've looped over each element and copied the values in the loop; 3) you can also copy multiple values at a time, which should be faster; 4) or simply use `memcpy`. – ForceBru Feb 12 '22 at 08:57