Can multiple variables be accessed with a single pointer in C++? | SoloLearn: Learn to code for FREE!

+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.

4/1/2018 3:40:25 PM

David Carroll

67 Answers

New Answer

+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

IMHO, no, because how can any primitive variable have more than one value at the same time? (Integer, boolean, etc.)

+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

+11

Check this number packing code https://code.sololearn.com/cGyipSIFVJro/?ref=app David Carroll , Please let me know if this is considered out of context post. I will remove it from here. Sorry in advance :)

+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

rudolph flash , First thing ISO C++ forbids converting a string literal to char* String literals are compile time constants and hence one could try to change (if char* was allowed) the value of the string constant. Unfortunately compilers only give warning and allow the code to compile. And when you try to change it will result in crash or sementation fault. Try this at sololearn compiler you can get a fault. char* ptr = "hello"; ---> generates warning *ptr or ptr[0] = 'H'; ---> crash One should always define string literals using std::strings but if one must use char* then it should be char const* ptr = "hello";

+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

At a given time a pointer can point to only one memory location, however you can have different data types share the same memory location in C/C++ using "union". Check link and read the notes at https://code.sololearn.com/ce4LYug0YIfN/?ref=app