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:
array
) in main
addVec
) 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 changeArray
declared like
void changeArray(double** vec1)
does not make sense. For example the pointer array
is passed to the function by reference through a pointer to it
changeArray(&array);
but the passed pointer is not changed within the function. The function declaration is senseless. You could declare the function at least like
void changeArray(double *vec1)
and call it like
changeArray(array);
To change elements of the array pointed to by the pointer array
there is no any sense to allocate dynamically one more array.
Nevertheless in any case the function has a bug in this for
loop
for (int i = 0; i < SIZE; ++i)
{
**(vec1 + i) = *(addVec + i);
}
Instead you need to write
for (int i = 0; i < SIZE; ++i)
{
*(*vec1 + i) = *(addVec + i);
}
That is at first you need to dereference the pointer vec1
to get an access to the original pointer array
and 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
int changeArray( double **vec1 )
{
double *addVec = calloc( SIZE, sizeof( double ) );
int success = addVec != NULL;
if ( success )
{
free( *vec1 );
double num = 1.0;
for ( int i = 0; i < SIZE; ++i )
{
*( addVec + i ) = num;
++num;
}
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");
*vec1 = addVec;
}
return success;
}
And in this case it is called like changeArray( &array )
.