I am a Python developer and new to C/C++. I am now reading "C Primer Plus" by Prata and trying to solve the exercises in the book.
In Chapter10, exercise 2, it requies to write a program that initializes an array-of-double and then copies the contents of the array into three other arrays. The first two functions work well. However, the third function puzzled me.
Here attached my codes and my questions:
#include <stdio.h>
void copy_ptrs(double *target, double const *source, double const *pos);
void show_array(double const ar[]);
int main(void)
{
double source[5] = {1.1, 2.2, 3.3, 4.4, 5.5};
double target3[5];
copy_ptrs(target3, source, source + 5);
return 0;
}
// Firstly I use parameter target directly, the results goes wrong.
void copy_ptrs(double *target, double const *source, double const *pos)
{
while (source < pos)
{
*target = *source;
target++;
source++;
}
show_arr(target);
}
// horrible result:
// -121700446960225610643551527831429232675085673090545663082496.000000 0.000000 0.000000 0.000000 0.000000
// Using pointer instead of target itself, the function works
void copy_ptrs(double *target, double const *source, double const *pos)
{
double *ptr = target;
while (source < pos)
{
*ptr = *source;
ptr++;
source++;
}
show_arr(target);
}
// correct result:
// 1.100000 2.200000 3.300000 4.400000 5.500000
I did some research and from these questions lvalue required as increment operand, Array increment operator in C
I know I cannot use increment operator in array names, however it doesn't answer why I can use ++ in source and why the using pointer for target or not has such different result.
With/without const in source has no influence in results.
Many thanks for any advice.