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;
}
**(vec1 + i)you're incrementing the wrong pointer. Instead do*(*vec1 + 1).