I am attempting to copy the elements of one dynamically-allocated array (addVec) into another (array) in memory, after passing a pointer to the array from main to a function (changeArray) that assigns values to addVec.
My approach thus far:
- Dynamically allocate an array (
array) inmain - Dynamically allocate another array (
addVec) inchangeArray() - Pass the pointer of this dynamically-allocated array and receive it in changeArray.
However, I am not sure how to correctly carry out steps 3 and 4, namely copying the elements of addVec into array.
void changeArray(double** vec1)
{
double* addVec = (double*)calloc(SIZE, sizeof(double));
double num = 1.0;
for (int i = 0; i < SIZE; ++i)
{
*(addVec + i) = num;
num = num + 1;
}
printf("Printing out addVec: \n");
for (int i = 0; i < SIZE; ++i)
{
printf("%.1f ", *(addVec + i));
}
printf("\nNow we want to copy elements from addVec to vec1.\n");
// Step 4
for (int i = 0; i < SIZE; ++i)
{
**(vec1 + i) = *(addVec + i);
}
free(addVec);
}
int main()
{
double* array = (double*)malloc(SIZE * sizeof(double));
double num = 11.0;
for (int i = 0; i < SIZE; ++i)
{
*(array + i) = num;
num = num + 1;
}
printf("The address of array is: %x \n", array);
changeArray(&array);
printf("The array is now: 1, 2, 3... \n");
for (int i = 0; i < SIZE; ++i)
{
printf("%.1f ", *(array + i));
}
free(array);
return 0;
}
The function
changeArraydeclared likedoes not make sense. For example the pointer
arrayis passed to the function by reference through a pointer to itbut the passed pointer is not changed within the function. The function declaration is senseless. You could declare the function at least like
and call it like
To change elements of the array pointed to by the pointer
arraythere is no any sense to allocate dynamically one more array.Nevertheless in any case the function has a bug in this
forloopInstead you need to write
That is at first you need to dereference the pointer
vec1to get an access to the original pointerarrayand then apply the pointer arithmetic the same ways as on the right side of the assignment statement.If you wanted to create dynamically a new array and reassign the passed pointer with the address of the newly dynamically allocated array then the function could look for example like
And in this case it is called like
changeArray( &array ).