0

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?

5
  • 1
    p is not incremented. Commented May 8, 2017 at 17:14
  • The problem with your code is that it changes p2, but it never changes p. Voting to close as a typo. Commented May 8, 2017 at 17:15
  • doing p++ gives random numbers mixed with some zeros as output in the memory locations Commented May 8, 2017 at 17:17
  • Eugene and das have both identified the problem; I'm just here to ask---why do it this way? When you use the [x] syntax, *(ptr + (x * sizeof(int))) is exactly what the compiler is doing (where int is the array type, as this example)... Commented May 8, 2017 at 17:18
  • because it is a requirement in our assignment. but when incrementing p with p++ it is not giving the correct output... Commented May 8, 2017 at 17:22

1 Answer 1

1

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);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.