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
Post a Comment