简体   繁体   中英

How to copy values from one array to another in C with pointer arithmetic

I am trying to copy the values from one array to another using strictly pointer arithmetic. This is the code I have right now:

   int *p;
   int arraySize = 20;

   int array[arraySize];     

   for (p = array; p< array+(sizeof(array)/sizeof(int)); p++){
        int random = rand() % 200;
        *p = random;
   }

   for (p = array; p< array+(sizeof(array)/sizeof(int)); p++){
        printf("%d\t%x\n", *p, p);
   }

   //the code above works fine

   printf("\n");

   //grow the new array by one to insert value at end later
   int array2[(arraySize+1)];

   int *p2;

   for(p2 = array2; p2< array2+(sizeof(array2)/sizeof(int)); p2++){
       *(p2) = *(p);
   }

   for(p2 = array2; p2< array2+(sizeof(array2)/sizeof(int)); p2++){
       printf("%d\t%x\n", *p2, p2);
   }

But when i run the code all that is outputted is 0 at each of the memory locations. what am i doing wrong that is preventing the values from being copied over?

Your problem is in this loop where you're copying from *p to *p2 :

for(p2 = array2; p2< array2+(sizeof(array2)/sizeof(int)); p2++){
    *(p2) = *(p);
}

You increment p2 but never increment p and you never reset p to point back to the beginning of array . At the beginning of this loop, p is pointing at the location just off the end of array . Change your loop to this:

for(p2 = array2, p = array; p2 < array2 + (sizeof(array2)/sizeof(int)) - 1; p2++, ++p){
    *(p2) = *(p);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM