can i change the value of an int with a pointer. e.q.
int n = 20;
int *size = n;
can i change n by doing this *size++.
thanx
Short answer: a pointer can change an int’s value only if it actually holds that int’s address and is safely dereferenced. As explained, assigning the integer value to the pointer makes an invalid address; dereferencing that is undefined behavior. Also, the postfix ++ binds to the pointer, so an expression like pointer++ advances the pointer (not the int). reiterated the precedence point.
Safer, clearer alternatives (modern C++):
int value = 20;
int &alias = value;
alias++; // increments 'value' directly via a reference A guarded pointer pattern:
int value = 20;
int *p = &value;
if (p) {
*p = *p + 1; // increment the integer via the pointer
} Practical cautions and tips:
This complements ’s correct explanation and gives practical, safer patterns for changing an int through indirection.
Jump to Post— mattjbond 54No. This will increment the pointer first and then deference the result. You would require paretheses here to achieve the result you want.
(*size)++This is because unary unary operators like ++ associate right to left..
Also you have a problem in that the expression
No. This will increment the pointer first and then deference the result. You would require paretheses here to achieve the result you want.
(*size)++ This is because unary unary operators like ++ associate right to left..
Also you have a problem in that the expression
int *size = n; is probably not doing what you intend. this is setting the pointer to an adress of 0x00000014 (20), not pointing it at n as you seem to desire. You need to use the address of operator to set size pointing to n.
int *size = &n; thnx, mattjbond
exactly,This will increment the pointer first and then deference the result. You need paretheses
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.