1

How do I change the value of a variable using a dynamic pointer or a smart pointer ?

int a=5;
int *b= new int(a);
*b=10;

cout<< a;

The output is 5. Is it possible for me to change the value of "a" using a dynamic or smart pointer?

3 Answers3

4
int *b = new int(a);

allocates a new int taking the same value as a. To point to a, just use

int *b = &a;

I don't know why you mention smart pointers here, they have no relevance. They are usually used for managing the lifetime of allocated memory, which you shouldn't be doing.

You can't learn C++ effectively by guesswork and experimentation. I suggest you pick up a good book.

Community
  • 1
  • 1
BoBTFish
  • 19,167
  • 3
  • 49
  • 76
2

You cannot make a dynamic pointer that points to an int allocated in automatic memory. If you would like to work with dynamic pointers, you can use std::shared_ptr, like this:

shared_ptr<int> a { new int(5) };
cout<< *a << endl;
shared_ptr<int> b { a };
*b = 10;
cout << *a << endl;

Demo.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0

Of course you can, but the line int *b = new int(a); is taking a value copy of a.

What's wrong with int* b = &a;?

Then you can manipulate a by dereferencing b.

Smart pointers will not help you here as they are concerned with managing the lifetime of something allocated with new. Your pointer is pointing to a variable with automatic storage duration.

P45 Imminent
  • 8,319
  • 4
  • 35
  • 78