Pages: [1]   Go Down
Author Topic: Pointer strange behavior  (Read 318 times)
0 Members and 1 Guest are viewing this topic.
Portugal
Offline Offline
Edison Member
*
Karma: 37
Posts: 1531
Pretending you know everything then you will learn nothing.
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Hello
I have this simple sketch
Code:
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)
Logged

Debian,Mint,Ubuntu
Arduino Mega 2560
Arduino Nano
Arduino Duemilanove
MAC OS Montain Lion
Raspberry PI Model B


Global Moderator
Dallas
Offline Offline
Shannon Member
*****
Karma: 197
Posts: 12740
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

Code:
(*ptr)++;
Logged

Portugal
Offline Offline
Edison Member
*
Karma: 37
Posts: 1531
Pretending you know everything then you will learn nothing.
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Code:
(*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?
Logged

Debian,Mint,Ubuntu
Arduino Mega 2560
Arduino Nano
Arduino Duemilanove
MAC OS Montain Lion
Raspberry PI Model B


Global Moderator
Offline Offline
Brattain Member
*****
Karma: 474
Posts: 18696
Lua rocks!
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

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:
foo = *ptr++;

That gets the current contents of ptr into foo, and then increments ptr.
« Last Edit: January 26, 2013, 07:15:46 pm by Nick Gammon » Logged

Pages: [1]   Go Up
Jump to: