使用c将数组和指针复制到源的最后一个元素之外

时间:2015-05-01 19:52:14

标签: c arrays pointers

是否可以初始化double数组,然后将内容复制到另一个数组中。程序应使用指针表示法的函数来复制原始源数组。

我应该使用的函数调用示例是copy_ptrs(copy,source和指向源的最后一个元素后面的元素的指针。)

这是我的主要参考资料

int main() 
{
    int i, num; 
    double source[MAX];
    double target1[MAX];
    double target2[MAX];
    double target3[MAX];


    printf("\nEnter number of elements to be read into the array: ");
    scanf("%d", &num);

    printf("\nEnter the values below (press enter after each entry)\n");

    for (i = 0; i < num; i++) 
    {
            scanf("%lf", &source[i]);
    }

    copy_arr(target1, source, num);
    copy_ptr(target2, source, num);
    copy_ptrs(target3, source, source + num);//This is how I was instructed to call the function.


    printf("\n\nCopying Complete!\n");

    return 0;
}

这是我的指针符号函数,用于简单复制

void copy_ptr(double target2[], double source[], int num)
{
    int i;
    double *p, *q;

    p = source;
    q = target2;

    for (i = 0; i < num; i++)
    {
            *q = *p;
        q++;
        p++;
    }

    printf("\n\n***The second function uses pointer notation to copy the elements***\n");
    printf("===================================================================\n");
    q = target2;

    for(i = 0; i < num; i++)
    {

        printf("\n              Pointer_Notation_Copy[%d] = %.2lf",i, *q++);
    }
}

这是使用数组表示法复制源数组的另一个函数

void copy_ptr(double target2[], double source[], int num)
{
    int i;
    double *p, *q;

    p = source;
    q = target2;

    for (i = 0; i < num; i++)
    {
            *q = *p;
        q++;
        p++;
    }

    printf("\n\n***The second function uses pointer notation to copy the elements***\n");
    printf("===================================================================\n");
    q = target2;

    for(i = 0; i < num; i++)
    {

        printf("\n              Pointer_Notation_Copy[%d] = %.2lf",i, *q++);
    }
}

当我尝试添加第3个函数来满足作业时,我会陷入困境。如何在源的最后一个元素后面指向元素?

void copy_ptrs(double target3[], double source[], int num)
{
    int i;
    double *p, *q;

    p = source;
    q = target3;

    for (i = 0; i < num; i++)
    {
            *q = *p;
        q++;
        p++;
    }

    printf("\n\n***The third function uses pointer notation to copy the elements + the number of elements read in?***\n");
    printf("===================================================================\n");
    q = target3;

    for(i = 0; i < num; i++)
    {

        printf("\n              Pointer_Notation_Copy[%d] = %.2lf",i, *q++);
    }
}

0 个答案:

没有答案