Why value in pointer not incrementing when I use increment operator - c++

int a=5; int *p=&a;
I want to increment the value of a so I tried below two methods but why they are giving different values
why a=*(p)++; is giving 5
but a=*(p)+1; is giving 6

In the line a=*(p)++; the () around p don't do anything and the line is parsed as a = (*(p++)); since postfix increment has higher precedence than indirection.
So you are incrementing the pointer, not the variable that the pointer points to. The postfix increment results in the value of the pointer before it was incremented, which you then dereference to give you the current value of a.
Then the line effectively becomes a = a;, doing nothing, except that p now points one-past a.
The line a=*(p)+1; is parsed as a = ((*p) + 1); since indirection has higher precedence than addition. This is effectively a = a + 1;, doing what you want.
There is however no point in using assignment at all. Just write (*p)++; to increment a through the pointer.

Related

Predict the output with pointers

In the code below, I'm confused about the working of 3 line.If anyone explains it ,I will be very grateful.
Thank you.
#include< iostream >
using namespace std;
int main()
{
1. char s[]="abcdef";
2. char *p=s;
3. *p++=*++p;
4. cout<<s;
5. return 0;
}
Before the line *p++=*++p;, p points to the start of the array s.
The ++p in the right hand-side of the line will increment p by one and so it now points to b. Dereferencing it with * will give the value b and so the right hand side evaluates to b.
In the left hand side, since the post-increment operator is used, the value of p will not immediately change. Thus, the value b from the RHS will be set to the same memory location. Because of the post-increment operator, p will point to the character c of the array.
Thus, the char array will remain the same after this line and so abcdef will be printed. p however will point to the character c of the array.
Note that the above is valid only since c++17. From en.cppreference.com/w/cpp/language/eval_order: In every simple assignment expression E1=E2 and every compound assignment expression E1#=E2, every value computation and side-effect of E2 is sequenced before every value computation and side effect of E1

C++ Precedence and Associativity

This piece of code:
int scores[] {1,2,3,4};
int *score_ptr {scores};
//let's say that initial value of score_ptr is 1000
std::cout<<*score_ptr++;
produces the output:
1
As * and ++ have same precedence and then associativity is from right to left shouldn't we apply ++ operator first that is to increase the pointer first and then *(dereference) it?
So accordingly score_ptr will be increased to 1004 and then dereferencing it will give the second element of scores which is 2.
How and why does this give me output of 1 instead of 2?
As * and ++ have same precedence
No, postfix operator++ has higher precedence than operator*; then *score_ptr++ is equivalent to *(score_ptr++). Note that the postfix operator++ would increment the operand and return the original value, then *(score_ptr++) would give the value 1.
The result is prvalue copy of the original value of the operand.
On the other hand prefix operator++ returns incremented value. If you change the code to *++score_ptr (which is equivalent to *(++score_ptr)) then the result would be 2 (which might be what you expected).
The increment will happen first, it has higher precedence, it's equivalent to *(score_ptr++), but it's a post-increment, this means it will only happen after the dereferenced pointer is used, i.e. the expression reaches ;.
If you use
std::cout << *++score_ptr;
Then you have a pre-increment, here it will happen beforehand, the pointer will be incremented before the value is used and the output will be 2. Equivalent to *(++score_ptr).
Note that it's allways a good idea to use parentheses, it will make the code clearer and will avoid missinterpretations.

What is the value of a pointer variable without the de-reference symbol?

I have searched all over for an explanation to the following code, and I can't find it anywhere. I know the output is 5, but can someone explain to me why it's 5? *b is equal to 2 after the 2nd to last line is evaluated, (I know why that is), but I don't know why b[3] equals 5. I just need the last line explained.
int* a = new int[10];
for(int i = 0; i < 10; i++)
a[i] = i;
int* b = &a[2];
cout << b[3];
After the assignment to b, it now points to the third element in the a array (i.e., the value "1").
The expression b[3] is equivalent to *(b+3) which means get the value which is three positions after b (this is essentially pointer arithmetic - b+3 is a pointer that is 3 positions after b. In this case 3 integers after b). So since b points to a[2], adding 3 makes it point to a[2+3] or a[5] which equals 5 (since the first loop makes a[i]==i).
cppreference: operator_member_access - Built-in_subscript_operator
The built-in subscript expression E1[E2] is exactly identical to the expression *(E1 + E2) except evaluation order (since C++17), that is, the pointer operand (which may be a result of array-to-pointer conversion, and which must point to an element of some array or one past the end) is adjusted to point to another element of the same array, following the rules of pointer arithmetics, and is then dereferenced.

Why can dereferenced pointers with postfix operators be expressed with parenthesis and still get the previous dereferenced value?

I do not understand the order of precedence here. Given:
*(p++)
Here is what I thought would happen:
(p++)
then
*p
Why isn't the address of p incremented first, then dereferenced, since the postfix is in the parenthesis?
*(p++)
Why isn't the address incremented and then dereferenced because of the parenthesis.
*p++ does not appear to be the same as *(p++), but they are the same.
In *(p++), the value of p is incremented by the p++, but the result of p++ is the value before the increment, and the * applies to the value before the increment. The parentheses are superfluous — arguably the mark of someone unsure of the language.
If you want to dereference the incremented value, you'd pre-increment:
*(++p)
*++p
Note that if you want to increment what p points at, you use:
(*p)++
++*p
++(*p)
The last two are the same, just spelled differently. The parentheses are necessary in the first of these three; *p++ is *(p++) and not (*p)++.
It is not about the order of precedence. It is about how postfix increment works.
What happens in p++ (assuming p is an int* for this simple example) is:
int* tmp = p;
p = p + 1;
return tmp;
so you are dereferencing the original value of p.

Pointer addition and element size

At: http://www.fredosaurus.com/notes-cpp/arrayptr/26arraysaspointers.html
Under: Pointer addition and element size
There is the following code:
// Assume sizeof(int) is 4.
int b[100]; // b is an array of 100 ints.
int* p; // p is a a pointer to an int.
p = b; // Assigns address of first element of b. Ie, &b[0]
p = p + 1; // Adds 4 to p (4 == 1 * sizeof(int)). Ie, &b[1]
How did "p" in the last line become "4"?
Thanks.
(I assume that you mean "1" in the last line, not "p")
Pointer arithmetic in both C and C++ is a logical addition, not a numeric addition. Adding one to a pointer means "produce a pointer to the object that comes in memory right after this one," which means that the compiler automatically scales up whatever you're incrementing the pointer with by the size of the object being pointed at. This prevents you from having a pointer into the middle of an object, or a misaligned pointer, or both.
because p is pointer to a type with size 4 bytes. + operator on pointers is actually pointer shift. compiler knows the size of pointed type and shifts it by appropriate value
if you change int to short, p will be shifted by 2 bytes
The comment in the code you post it explains it: addition of an integer x to a pointer increases the pointer's value by x multiplied by the sizeof the type it is pointing to.
This is convenient because it doesn't usually make sense to change the pointer in smaller increments - you wouldn't want it to point into the middle of one of the elements.