+ 61
Can multiple variables be accessed with a single pointer in C++?
Of the many languages I've worked with over the years, C/C++ are two I have worked with the least. I came across an answer by nonzyro where the following was posted in an answer: "You can access multiple variables with a single pointer." - nonzyro See: https://www.sololearn.com/Discuss/1181282/?ref=app I am hoping nonzyro (or anyone else) could clarify this statement. [UPDATE]: Although I accepted an answer already, there are quite a few really good responses in this thread worth reviewing.
63 Respostas
+ 6
Hey all, I noticed I got tagged in this thread a little.
To clarify my answer in the previous thread, I was simply talking about a pointer being reassign-able among multiple same types.
Going deeper, I'll brush on a C-ism here, but void pointers can point to anything, so long as they're cast right when accessing the data. The following function is an example of one method of "C overloading":
int func (void *ptr, char ptype)
where ptype is passed to let the function know how to treat the pointer (you've probably used structs with a type flag before, this is just more flexible).
You can, as already mentioned, use a pointer array since pointers themselves are a fixed size (depending on architecture). This is actually a struct in essence.
I hope I've disambiguated _what I meant_ and also _answered the question_.
At some point, I'll try to put up some decent example code (this editor is horrible). For the meantime, I hope that clarifies, although judging by some posts, I see a few of you have a firm grasp and are probably _better at explaining_ than I.
+ 48
Storing a memory address in a pointer, and then reassigning another memory address to it, is in no way, a proof that pointers can access multiple variables. It simply means that the pointer is used to store one memory address at one time (which is true).
The only thing which makes sense to me (at legitimising the argument) is to access other objects "near" the memory address stored by the pointer.
*(ptr + 1)
This way, we can claim that we are able to obtain the values of other (and hence multiple) variables, given the address of a single variable. However, this requires prior knowledge that data is already stored consecutively like those within an array.
+ 16
Wow... great responses everyone. Thanks for taking the time. I've been busy with the family today. Will respond later tonight or tomorrow. Current time for me is Sunday, April 1 - 9:15PM.
+ 13
Pointers are variables, they stores adresses and because they are variables you can assign a value..
int* ptr ; // declaration
ptr = &someVar; // assignment
ptr = &anotherVar;
idk if make sense to use one pointer for different objects but it's always up to the programmer.
For example an iterator may be the case..
for(vector<T>::iterator it = .....)
{ cout<<*it
We also have references but they are not variables.. they are just references, you cannot assign a reference, it point always the same obj.
int& ref ; // error! you must define at declaration time!
+ 11
Yes David sir,
we can access mutiple variables with a single pointer...go through this code you will clearly find your answer
https://code.sololearn.com/cC50vo3CIvqc/?ref=app
+ 10
James - That is an excellent "pointer"... pun intended. š¤
I hadn't considered this as the meaning. But, I can see this being what nonzyro might have been referring to.
--
Yesh Jadav - Thanks for the code to demo this in action.
--
Hatsy Rei - I doubt this is what nonzyro was referring to in the other post. However, I do agree the concept of deriving memory address with something like:
*(ptr + 1)
is theoretically more sound - in a pure academic argument. š
--
@Ozren, I agree with Alex, I don't think this is what nonzyro was referring to. I could be wrong. š
--
Alex - Awesome demo of storing decimals as hex using bit shifting operations.
I'm gonna need to step through this with a debugger to see lines 121 - 127 in action. š
--
Chris - I agree... However, use of an array of pointers gets further way from what I think nonzyro was referring to. Hopefully, we'll get a response from the original person.
--
Jay Matthews - I was thinking the same thing which is what prompted me to ask this question.
--
So far, we've had various different suggestions all with interesting food for thought. I truly appreciate all the input and the code people wrote for this response.
In the end, I'm going with the answer I believe to explain what nonzyro might have been referring to and that will be James.
+ 10
~ swim ~ Not only is your answer well within context, it's much appreciated. š
+ 10
@ALL people don't worry about stupid meaningless downvoters.
If someone do this for no reason .. no reason to worry about
+ 10
~ swim ~ š thank you for your diligence and sharing your precious knowledge!
+ 9
Technically, you could have a pointer pointing to an array of pointers. This way you can use a single pointer to access multiple variables with the method Hatsy explained. Those variables don't even have to be stored consecutively in the memory then, but of course their memory addresses in the array are.
+ 9
Prem Jaiswal We generally discourage the misuse of downvotes. Was there a legitimate reason to go on a downvote spree on this thread?
+ 9
~ swim ~ thank you for pointing out!
My answer was a bit generic..
In fact is interesting how a reference must be inside initializer, more or less like const variables
+ 8
1)
char* p = "Hello World";
places a string literal in read-only memory and makes p a pointer to that location. Writing operations are illegal for this. (You should also get a compiler warning, because you assign a const char* to a char*.)
2) char p[ ] = "Hello World";
puts the elements of the string in an array on the stack and the elements can be modified, because each element has an own memory location.
+ 8
i think just the two-dimensional array with single pointer is possible.
int a[3][4],*p;
p=a[0]; or p=*a; or p=&a[0][0];
+ 7
Ugh... The user mention feature flaked out on me. Apologies if my answer got distorted.
+ 7
Noman Khan In c++ void pointers shouldn't be used without a good reason. And even if you have a reason: think again if there is no better way.
The only scenario I have in mind when a generic pointer is need would be if you use some routine from a c library which requires you to use them.
In c void pointers are really useful and more often needed though because you need to work with raw memory more often.
+ 7
Wait.. whaaat! Usefulness of pointers??
Ok store the address of an existing variable in a pointer is not really useful generally.
=> Pointers are necessary in dynamic memory, when you allocate memory with "new" it returns a pointer, you need it to work with and to deallocate memory, it's really important to do it , memory leaks easily!
Rule: always delete what you new!
C++ offers smart_pointers to better manage resources!
https://en.cppreference.com/book/intro/smart_pointers
A really important pro of smart pointer: "it does not matter if the function scope is left through the return statement, at the end of the function or even through an exception, TheĀ unique_ptr<>Ā destructor is always calledĀ " [reference]
-use pointers only when needed
-use smart pointers is better
-C++ has references, use it !
Use pointers if references cannot do the job.
- use C++ casts, use C casts only if necessary or better review all your design.
https://stackoverflow.com/questi
=>polymorphism and inheritance requires pointers
+ 6
actually James you will require more this pointers in big arena we usually cannot avoid this pointers bcoz this pointers will help throughout our life ...you will understand this through hackerrank
+ 6
Using structs is kinda cheating :P
But if we start to go this way:..
You don't even need a pointer to store multiple variables in a single memory location.
https://code.sololearn.com/c6K2jshJcG6y/?ref=app
+ 6
You can try to check your suggestion as following:
1. declare two variable of the same type and assign two different value to them
2. then create a pointer to the first one,
3. calculate how much memory space occupates this type of variable
4. try to read both variables. First one via pointer itself and the second one via pointer shifted (e.g. increased) by the appropriate number of bytes.
If you have luck and your compiler assigned the memory locations in a row, you will
get the values, assigned at the step 1.
P.S. do NOT write anything to the second location!