I have a question about the C language pointer.

Asked 2 years ago, Updated 2 years ago, 28 views

/* 10.2.c -- A program that copies an array in three ways.*/

int main(void) {

double source[5] = {1.1,2.2,3.3,4.4,5.5};
double target1[5] = {1.0,1.0,1.0,1.0,1.0};
double target2[5] = {1.0};
Double target3[5]; // array declaration.

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

printk(target1,5);
printk(target2,5);
printk(target3,5);
return 0;

}

void copy_arr(double * target1,double * source,int n) {

inti; // function definition and region variable declaration

for(i=0;i<n;i++){
    target1[i] = source[i]; // Copy and insert array values
}

} void copy_ptr(double * target2,double * source,int n) {

int i;
double * a=target2;
double * b=source; // function definition and region variable declaration

for(i=0;i<n;i++)
{
    *a = *b;
    a++,b++; // Copy and insert with array value pointer
}

}

void copy_ptr2(double * target3,double * source,double * end) {

double * a,*b; // function definition and region variable declaration

for(a=target3,b=source;a<end;a++,b++)
{
    *a=*b; // Copy and insert with array value pointer
}

}

void printk(double * target,int n) {

int i;
double * s=target;
for(i=0;i<n;i++)
    printf ("Copy: %").2f\n",*(s+i)); // Output Array

printf("\n");

} I'm asking you a question because I don't know even if I think about it for an Copy is a function that copies an array, and printk is a function that outputs an array, so only copy_ptr2 is copied and printed in a proper way. What's the problem?

c

2022-09-22 10:51

1 Answers

When I ran it,

copy_arr(target1, source, 5);
copy_ptr(target2, source, 5); 

The above functions operate normally

copy_ptr2(target3, source, source + 5);

Only this function was not copied properly.

The reason is We put source + 5 in the parameter end, but the conditional expression that goes in the middle of the for statement inside the actual function has a pointer called a that points to target3, not source.

Therefore

for (a = target3, b = source; b < end; a++, b++)
{
    *a = *b; // Copy and insert with array value pointer
}

I'll doable.


2022-09-22 10:51

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.