Counter variable gets reset to 0 without resetting it(Mega) (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 ?!

Code:

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

void setup() {
Serial.begin(9600);
}

void loop() {  
for(i=0; i&lt;245 ;i++){
  *b++=data;
  data++; 
  delay(50);
  n++;
  Serial.println(buf[i]);
  }
  data=0;
  delay(5000);
  Serial.println("counter:");
  Serial.println(n); 
  delay(5000);
}
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;