-1

I have a few issues understanding the left shift operator. I know that if shifts by x amount of bits to the left, therefore pretty much multiplying the number to 2 to the power of the number of bits shifted.

But consider this program:

int a=4,*pA=&a,r3;
printf("%d\n",pA);
printf("%d\n",(*pA<<2));
r3=pA-(*pA<<2);
printf("%d",r3);

It prints out pA, and (*pA<<2) separately, and if you were to subtract these two, it won't equal to the r3 written in the expression, being off by 4 times, which is the size of int. But where do you need to take the size of int into consideration, since you have both pA and (*pA<<2), and their subtraction doesn't equal to what it's supposed to.

Any help is appreciated...

For the record, I am not interested in printing out the actual value of the pointer, but actually its address being shifted by 2 bits. And I don't understand the exact process that is happening.

2 Answers2

5

Arithmetic on a pointer scales with the size of what it points to. So when you do pA - 80 your code actually does pA - 80*sizeof(*pA). This has nothing to do with <<.

Also you should print addresses using the %p format specifier. And to store pointer values in an integer type use intptr_t or uintptr_t (from stdint.h). Enable warnings on your compiler and it should complain if you don't do this.

Kevin
  • 6,993
  • 1
  • 15
  • 24
1

The dereference operator * has higher precedence than the left-shift operator <<. So the expression *pA<<2 actually evaluates to (*pA)<<2. This give you the value pointed to by pA, i.e. a left shifted by 2.

It seems like what you want is pA<<2, however a pointer is not a valid operand to the << operator. Multiplying a pointer value is not defined, nor does it makes sense. You can however add to or subtract from a pointer.

The index operator [] is a syntactic sugar around adding to a pointer and dereferencing, so you could use that. However, pA points to a single int, not an array, so doing so is undefined behavior.

dbush
  • 205,898
  • 23
  • 218
  • 273
  • No, I indeed want it to be shifted by (*pA)<<2. –  Jan 20 '17 at 20:15
  • 1
    @Radu That's what you're doing now, i.e. shifting the value not the pointer. Shifting a pointer makes no sense. – dbush Jan 20 '17 at 20:17