0

This what I have right now it will not print the first or last number, I'm not sure why it's not

#include <stdio.h>
int main(){
  int i, j;
  float ar[5] = {12.75, 18.34, 9.85, 23.78, 16.96}, br[5];
  float *ptrAr, *ptrBr;
  ptrAr = ar;
  ptrBr = &br[4];
  for ( i = 0; i < 5; i++) {
    *ptrBr = *ptrAr;
    ptrAr++;
    ptrBr--;
  }
  for ( i = 0; i < 5; i++) {
    printf("%5.2f\n", *ptrBr);
    ptrBr++;
  }
  return 0;
}
2
  • Hi, this is a good task for a debugger, it is not simple to see an error in someone's code. Try using it and you may see the error easily. Btw, what is the result that is actually printed - first and last as 0? Commented Apr 14, 2014 at 20:14
  • 1
    @TomasPastircak: Debuggers might not find Undefined Behavior at all. Commented Apr 14, 2014 at 20:22

4 Answers 4

2

Your code has undefined behavior, because ptrBr is set to br-1.
That means anything can happen, even the proverbial nasal demons:

ptrBr = &br[4];
for ( i = 0; i < 5; i++) {
  *ptrBr = *ptrAr;
  ptrAr++;
  ptrBr--;
}

Change the loop to this:

ptrBr = br+5;
for(i = 0; i < 5; i++)
  *--ptrBr = *ptrAr++;

That will also fix your output, because ptrBr == br at this place now.

Sign up to request clarification or add additional context in comments.

Comments

1

reset your ptrBr before your print loop

ptrBr = br;

Comments

0

Just add an additional ptrBr++; after the 1st for loop. Since the last execution of your 1st for loop did an extra ptrBr--;

                ptrBr++;
        for ( i = 0; i < 5; i++) {
                printf("%5.2f\n", *ptrBr);
                ptrBr++;
        }
        return 0;
}

Comments

0

Your program invokes undefined behavior as it access unallocated memory. In fact ptrBr points one element before the array br at the end of loop.
Change your for loop body to

for ( i = 0; i < 5; i++) {
     printf("%5.2f\n", *++ptrBr);
}

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.