1

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.

agent1894
  • 11
  • 1
  • 1
    Dear all, I found the bug. The assigning part works fine, the wrong part is the show_array() func. Since I use the ++ to move the pointer, when I tried to print the array, it starts at the end of the target array and out of the bound. If I move the show_arr() func into main(), the output is OK – agent1894 Mar 09 '21 at 09:45

1 Answers1

0

target++ changes the value of target. So after the loop:

while (source < pos)
    {
        *target = *source;
        target++;
        source++;
    }

target no longer points to the start of the destination array andshow_arr(target); cannot work.

In contrast, the code:

    double *ptr = target;
    while (source < pos)
    {
        *ptr = *source;
        ptr++;
        source++;
    } 
    show_arr(target);
}

makes a copy of target and alters the copy, leaving target unchanged.

Eric Postpischil
  • 168,892
  • 12
  • 149
  • 276