(Arduino Mega2560) I'm trying to test placing a counter n in a for loop, the problem is, every time it gets out and goes back to the for loop, the n is reset again, so it prints "counter: 245" every time. However, when I comment out *b++=data; and data++; it does count properly. What exactly is going on ?!


uint8_t i=0;
uint8_t buf[245];
uint8_t *b=buf,*b2=buf;
uint8_t data=10;
int n=0;

void setup() {

void loop() {  
for(i=0; i<245 ;i++){
  • 2
    b is heading off into the unknown and you're blasting all your other variables with junk.
    – Majenko
    Mar 31 '20 at 14:49
  • Oh I see ! I have never tried pointers before, can I do b=0 to reset it or it's done a different way ? Mar 31 '20 at 14:55
  • b = buf; will reset b to the start of the buf variable memory area. Your b++ goes up and up and up otherwise with no limit. After 254 increments it will be pointing at something after buf - which sounds like n to me.
    – Majenko
    Mar 31 '20 at 14:57

You never reset your b pointer. The first time through it works its way through the memory reserved for buf. The second time through your loop it's already at the end of that memory and you then start incrementing (and filling) past that overwriting other variables - the first of which sounds like it might be n - so *b++=data is writing data (245) to n.

You need to reset b each time you go through loop so it starts at the beginning of the array each time:

b = buf;
  • Thanks Majenko, it makes sense now. Mar 31 '20 at 15:02
  • @Majenko ... upvoted ... my mistake indeed. Mar 31 '20 at 15:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.