10.13-2 数组拷贝

三种方式实现数组的拷贝
调用如下函数

const double source[SIZE] = { 1.1,2.2,3.3,4.4,5.5 };
double target1[SIZE] = { 0 };
double target2[SIZE] = { 0 };
double target3[SIZE] = { 0 };

copy_arr(target1, source, 5);
copy_ptr(target2, source, 5);
copy_ptrs(target3, source,source+SIZE);

程序示例

/* 10.13.2 */
#include
#define SIZE 5
void copy_arr(double target1[], const double source[], int m);
void copy_ptr(double *target2, const double *source, int m);
void copy_ptrs(double *target3, const double *source, const double *end);
int main() 
{
    const double source[SIZE] = { 1.1,2.2,3.3,4.4,5.5 };
    double target1[SIZE] = { 0 };
    double target2[SIZE] = { 0 };
    double target3[SIZE] = { 0 };

    printf(" the orgin arry:\n ");
    for (int i = 0; i < SIZE; i++)
        printf("%8.3lf", source[i]);
    putchar('\n');
    copy_arr(target1, source, 5);
    copy_ptr(target2, source, 5);
    copy_ptrs(target3, source,source+SIZE);
    for (int i = 0; i < SIZE; i++)
        printf("%8.3lf ", target3[i]);
    putchar('\n');

    getchar();

    return 0;
}
void copy_arr(double target1[],const double source[], int m)
{
    printf(" the arry target1:\n");
    for (int i = 0; i < m; i++)
    {
        printf("%8.3lf", target1[i] = source[i]);
    }
    putchar('\n');
}
void copy_ptr(double *target2, const double *source, int m)
{
    printf(" the arry target2:\n");
    for (int i = 0; i < m; i++)
    {
        //此处若为 target2+i = source+i 则属于const指针赋予非const指针,是不安全的
        //因此,采用对存储在地址的数据值传递的方式进行操作
        printf("%8.3lf",*(target2 + i) = *(source + i));
    }
    putchar('\n');
}
void copy_ptrs(double *target3, const double *source, const double *end)
{
    printf(" the arry target3:\n");
    while (source < end)
    {
        *target3=*source;
        source++;
        target3++;
    }
}

你可能感兴趣的:(10.13-2 数组拷贝)