Go Down

Topic: Pointer strange behavior (Read 433 times) previous topic - next topic

HugoPT

Hello
I have this simple sketch
Code: [Select]
char A = 49;
char * ptr = &A;

void setup()
{               
Serial.begin(9600);
Serial.println(A);
}
void loop()
{
*ptr++;
Serial.print(A);

delay(1000);
}

The pointer variable ptr points to variable A, so ptr have the address of A using &A.
So I suppose when I increment pointer using *ptr++  ( pointed by ptr)  I will increment char A indirectly.
Well I can't figure out what is happen here since the output is always 1 ( 49 in Decimal)
Debian,Mint,Ubuntu
Arduino Mega 2560
Arduino Nano
Arduino Duemilanove
MAC OS Montain Lion
Raspberry PI Model B

Coding Badly


HugoPT

Code: [Select]
(*ptr)++;
It works but can you explain me why does I need the parenthesis?
Wasn't suppose to increment it that way?
What I'm increment then using *ptr++ , his address?
Debian,Mint,Ubuntu
Arduino Mega 2560
Arduino Nano
Arduino Duemilanove
MAC OS Montain Lion
Raspberry PI Model B

Nick Gammon

#3
Jan 27, 2013, 01:11 am Last Edit: Jan 27, 2013, 01:15 am by Nick Gammon Reason: 1
Operator precedence. You are incrementing what the pointer points to, without the brackets.

You are incrementing the pointer (I got that wrong).

http://en.wikipedia.org/wiki/Operator_precedence_in_C#Operator_precedence

Thus it is fairly normal to write:

Code: [Select]

foo = *ptr++;


That gets the current contents of ptr into foo, and then increments ptr.
Please post technical questions on the forum, not by personal message. Thanks!

More info:
http://www.gammon.com.au/electronics

Go Up