I need to write a function that makes a deep copy of an array of integers, using only pointer arithmetic (i.e. cannot use array-element syntax like orig[i]).
The first argument is the array to copy, and its length is specified by the second argument.
Here is what I have so far:
int* copyArray(const int *orig, int size) {
int *copy = malloc(size * sizeof *copy);
int **toReturn = ©
for (int i = 0; i < size; i++, orig++, copy++) {
*copy = *orig;
}
return *toReturn;
}
int main () {
int testArray[3] = {1, 2, 3};
int *testptr = testArray;
int *copied = copyArray(testptr, 3);
for (int i = 0; i < 3; i++) {
printf("%d %p", testArray[i], &testArray[i]);
printf("\n");
}
printf("\n");
for (int i = 0; i < 3; i++) {
printf("%d %p", copied[i], &copied[i]);
printf("\n");
}
return 0;
}
This isn't getting me the right results... The result I get from this is:
1 0x7ffce0ff6fd0
2 0x7ffce0ff6fd4
3 0x7ffce0ff6fd8
0 0xe1301c
0 0xe13020
0 0xe13024
whereas it should be:
1 0x7ffce0ff6fd0
2 0x7ffce0ff6fd4
3 0x7ffce0ff6fd8
1 0xe1301c
2 0xe13020
3 0xe13024
I'm new to pointers and memory allocation... What am I doing wrong?
UPDATE: Problem fixed!
Look at my answer, or the other answers that work as well.
copy
, so when you return it, it points to the end of the array. Also, you're allocating only 3 bytes of memory; it should bemalloc(size * sizeof *copy)
. Third problem found: usesize
in the for loop incopyArray()
, not3
.copy++
. That changes the value you return. The value ofcopy
that you get frommalloc
needs to be returned unchanged from yourcopyArray
function.copy
pointed to before you didcopy++
. AlsotoReturn
is redundant, what you have now is the same asreturn copy;
.