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

Dani AI

Generated

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:

  • Pointer arithmetic moves by sizeof(the pointed type). Incrementing a pointer to a single automatic variable does not “increment the variable”; it makes the pointer point elsewhere and can easily become invalid.
  • Always initialize pointers (prefer nullptr for no target) and avoid dereferencing unless the pointee’s lifetime is guaranteed.
  • For simple aliasing, prefer references; for ownership, prefer smart pointers (std::unique_ptr/std::shared_ptr).
  • For details on how operators bind and pointer rules, see C++ operator precedence and pointers in C++.

This complements ’s correct explanation and gives practical, safer patterns for changing an int through indirection.

Recommended Answers

All 3 Replies

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.