c++ - Incrementing pointer prints garbage? -


i wrote following code:

void incrementnumber(int *num) {     *num++;     printf("%i\n", *num); }  int main() {     int = 3;     printf("%i\n", i);      int *ptr = &i;      incrementnumber(&i);     printf("%i\n", i);      getchar();     getchar();      return 0; } 

whenever output num in increment number, prints garbage, if change code this:

void incrementnumber(int *num) {     *num += 1;     printf("%i\n", *num); } 

it outputs values expected. i'm trying away using references can better understand pointers because (like most) knowledge of pointers limited , i'm trying grasp them better.

also let me rephrase question, know why outputs garbage value, it's because it's incrementing memory address , printing garbage @ location rather incrementing value contained @ memory address, guess i'm asking why on increment not add to? way 2 commands compile down assembly? there way increment value pointed pointer in way?

that's because of precedence: *num++ evaluated num++ , dereferenced. when print value next, invalid pointer in case.

if use (*num)++, you'll result want.


Comments

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -