Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Incrementing pointer prints garbage?

Tags:

c++

c

pointers

I wrote the following code:

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

int main()
{
    int i = 3;
    printf("%i\n", i);

    int *ptr = &i;

    incrementNumber(&i);
    printf("%i\n", i);

    getchar();
    getchar();

    return 0;
}

Whenever I output num in increment number, it just prints garbage, however if I change the code to this:

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

It outputs the values as expected. I'm trying to get away from using references so I can better understand pointers because (like most) my knowledge of pointers is fairly limited and so I'm trying to grasp them better.

Also let me rephrase the question, I know why it outputs that garbage value, it's because it's incrementing the memory address and printing the garbage at that location rather than incrementing the value contained at the memory address, what I guess I'm asking is why does it do that on an increment but not with an add to? Is it just the way those two commands compile down to assembly? Is there a way to increment the value pointed to by a pointer in this way?

like image 787
Trevor Hart Avatar asked Feb 06 '16 03:02

Trevor Hart


2 Answers

That's because of precedence: *num++ is evaluated as num++ and then dereferenced. When you print the value next, it is from an invalid pointer in this case.

If you use (*num)++, you'll get the result that you want.

like image 96
user1952500 Avatar answered Oct 24 '22 04:10

user1952500


I'm glad you understand what happens in this line:

*num++;

The problem is the operators' priority. I believe that '++' has priority over '*' (in this context, of course). Try writing this, it'll work the way you want:

(*num)++;

One thing I didn't know and just learned is that the pointer operation in this context has higher priority over +=.

like image 28
Judismar Arpini Junior Avatar answered Oct 24 '22 05:10

Judismar Arpini Junior