-1

I have two code with different output.Need a good explanation, how its working in memory.

#include "stdafx.h"

int *fun(int *j)
{
    *j++;
    return j;
}

int _tmain(int argc, _TCHAR* argv[])
{
    int i = 10;
    int *j,*k;
    j = &i;
    k = fun(j);
    printf("Now the value = %d",i);
    printf("Now the value = %d",*j);
    printf("Now the value = %d",*k);
    return 0;
}

Here output is : 10,10 and -(some value).

If I change the bracket like following then:

#include "stdafx.h"

int *fun(int *j)
{
    (*j)++;
    return j;
}

int _tmain(int argc, _TCHAR* argv[])
{
    int i = 10;
    int *j,*k;
    j = &i;
    k = fun(j);
    printf("Now the value = %d",i);
    printf("Now the value = %d",*j);
    printf("Now the value = %d",*k);
    return 0;
}

Here output is : 11,11,11

This is I'm doing in Visual studio.Please give a good explanation.Thanks.

Matthew Champion
  • 400
  • 7
  • 18
bapi
  • 1,903
  • 10
  • 34
  • 59

2 Answers2

1

The problem here is operator precedence. Because the suffix ++ operator has higher precedence than the dereference operator * the increment is being done on the pointer and not the value being dereferenced.

So the function returns the increased pointer, which now points to somewhere else, so the dereference of k in main will be undefined behavior.

Jens
  • 69,818
  • 15
  • 125
  • 179
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0
*j++;
return j;

This increments the pointer j, and then returns the incremented pointer. There are two possible ways to interpret *j++: either increment j, or increment *j. But because post-increment ++ has higher precedence than pointer de-reference, the interpretation is to increment j.

Note that the behaviour of this version of the program is undefined because there is no guarantee that the pointer you return is valid. Anything at all could happen when you run this version of the program.

(*j)++;
return j;

Here the parentheses specify which interpretation to use, and override rules of precedence. This code increments the value which j points to, and does not modify j. Thus the return statement returns the original pointer. This version of the code does at least exhibit well-defined behaviour.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490