0

Say I have an existing array int *array

int *new_array = NULL;
new_array = array;
int *copy(int *array)
{
return array;
}

int* new_array = NULL;
new_array = copy(array);

What's the difference between the two?

Thanks for the help!

4
  • 6
    no difference except a function call, the result is exactly the same. Notice that you copied nothing, after operation both array and new_array points to the same address, meaning, the same data. Commented May 17, 2022 at 21:12
  • 3
    The two code snippets do the same thing, and in particular, neither one makes a copy of the array. Commented May 17, 2022 at 21:14
  • look at memcpy if you want to actually copy the data from array to new_array. Commented May 17, 2022 at 21:19
  • Does the actual code you are having a problem with look more like int *foo(void) { int array[something]; return array; } than int *copy(int *array) { return array; }? Commented May 17, 2022 at 21:40

1 Answer 1

1

Arrays cannot be assigned in C language. In your examples, you assign a pointer with reference to the first element of the array. Your second snippet also only assigns pointer with pointer returned by the function. It does not copy data referenced by those pointers.

Say I have an existing array int *array

It is not an array - it is a pointer to int

If you want to copy elements of one array to another array you need to use function memcpy or memmove

int array1[5] = {1,2,3,4,5}
int array2[5];

memcpy(array2, array1, sizeof(array1));
Sign up to request clarification or add additional context in comments.

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.