Can you help me with this code

When i compile this code, i get that c is 40, but I dont understand why is that.. If anyone can help me it would be good..
1
2
3
4
5
6
7
8
    int a,b,*pa,*pb,c,d;
    pa=&a;
    pb=&b;
    scanf("%d%d",pb,pa);
c= *(++pa);
    d=++(*pb);
    printf("a=%d,b=%d,c=%d,d=%d",*pa,*pb,c,d); 
return 0;
What is your user input?

Well, regardless of what your user input is, your program invokes undefined behavior. On line 5 you are incrementing the pa pointer, and then dereferencing it. But there is no guarantee that the pa pointer now points to valid memory.
Last edited on
I certainly don't get c=40 when I run the code using Visual Studio 2019:
1
2
3
4
5
6
7
8
9
10
11
12
#include <cstdio>

int main()
{
   int a, b, * pa, * pb, c, d;
   pa = &a;
   pb = &b;
   scanf("%d%d", pb, pa);
   c = *(++pa);
   d = ++(*pb);
   printf("a=%d,b=%d,c=%d,d=%d", *pa, *pb, c, d);
}

5 6
a=9216000,b=6,c=9216000,d=6

pa and c point to a memory address your program doesn't own, never initialized. That is undefined behavior.
This is 'c hacking at its worst'. The result is undefined as it depends upon how the compiler lays out's its variables in memory.

If we consider:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <stdio.h>

int main()
{

	int a, b, * pa, * pb, c, d;
	pa = &a;
	pb = &b;
	scanf("%d%d", pb, pa);
	printf("&a: %p, &b: %p, &pa: %p, &pb: %p, &c: %p, &d: %p\n", pa, pb, &pa, &pb, &c, &d);
	c = *(++pa);
	d = ++(*pb);
	printf("a=%d,b=%d,c=%d,d=%d", *pa, *pb, c, d);
	return 0;
}


Then for input
 2 31 
I get for VS2019 64bit:

1
2
&a: 00000000001FF994, &b: 00000000001FF998, &pa: 00000000001FF980, &pb: 00000000001FF988, &c: 00000000001FF990, &d: 00000000001FF99C
a=3,b=3,c=2,d=3


OK. The address of a is 1FF994 and the address of b is 1ff998. b has the value 2 and a has the value 31 (scanf is b then a, not a then b as might be expected!).

pa is incremented so is now 1ff998. This is the address of b. *(1ff998) is the value of b so c is now 2.

pb is 1ff998 so *1ff998 is 2. So d is 2 + 1 which is 3

The final output 'lies' as a is not 3, but is still 2. *pa is 3 as pa is now the same as pb.

This all assumes that &b has a higher address than &a - but is probably true for some compilers/systems but shouldn't be assumed.

But notice that the address of c is 1ff990 - which is the address before that of a!

So the memory layout is:


1ff980 - pa (64 bits as compiled as 64 bit)
1ff988 - pb (64 bits)
1ff990 - c (32 bits)
1ff994 - a (32 bits)
1ff998 - b (32 bits)
1ff99c - d (32 bits)


These do not correspond to the order of definition! So really, no assumption should be made about any memory ordering of variables!
Last edited on
Topic archived. No new replies allowed.