Question:
C++ - What are the uses of pointers, specifically?
?
2012-01-19 09:41:39 UTC
Can you give examples of when they would be useful, I mean why can't we just use variables all the time instead.

I'm new to C++. Thanks.
Seven answers:
Rainmaker
2012-01-19 10:23:29 UTC
The question is difficult to answer precisely. Many people will tell you not to use them if you don't have to, other people will tell you that they are a must.



Pointers make it easier to pass data from one chunk of code to another, but they can also create a lot of problems.



If you are happy doing what you're doing, stick with it. If you're going to start writing code with linked lists, etc, you will need the basics of pointers though.



A useful example?

I need a buffer for data, but I do not know how big it needs to be until run-time, so I declare a pointer and allocate memory for the buffer when I know how big it needs to be.



char *buffer; UINT filesize;

buffer = malloc( sizeof(char) * filesize );
Bob M
2012-01-19 14:38:03 UTC
I can understand this sort of confusion with pointers, because with the modern 'managed' languages much of what you would do with a pointer is hidden from you. Even in managed C++you could live without pointers.



Think first of a visual basic or C# data array defined by this -



List listOfFiles = new List();



This is an array of the structure class 'FileInfo'.



The declaration and all of the handling is done for you. You can create lists and lists of lists and never have to worry about how large a structure of data is, you are even protected from falling off the end of a list or trying to make use of an object that has not yet been assugned. You can traverse the array with an index value or use a built in iteration method.



There is nothing wrong with that level of programming safety, but it is not available everywhere and there are places where it does not work well. There is also another side, the 'managed' manner of these constructs means that for every operation you perform on the data array however simple has a heavy overhead from the code that protects you from boundary errors, null errors, traversing structures of the same types but of different sizes. You can even have lists of objects of different types without worrying about the data size.



If you ever find yourself working with embedded C++ or machine control, there may be classes that offer some amount of automation with data structures, but there will not be any that give the same level of protection as the 'managed' code does.



In your tutorials you have no doubt come across structures and data classes and building arrays for those



struct

{

int* anInteger';

struct

{

char* characterArray;

}

}



You have to build an array of the above structure, I have made it easier because this struct will always be the same size. But where are you going to put the data, the int that is pointed to and the char* that is pointed to.?



Ok, use malloc or calloc, maybe on the global heap, maybe on the stack. Application stack or create your own stack just for data?



This is all the work of pointers, as you work with them through your tutorials then using them and making decisions on their use will become second nature.



Practice practice, and when you think you have it all worked out, practice some more. It is all worth while, let me tell you why.



Though there is a lot can be said for 'managed' languages on Windows operating systems, there is something that programmers everywhere get frustrated with at some time in their work. It is that you are too far removed from the underlying hardware. Windows, as Linux is, is a shared resource system, however, UNIX and Linux know that just because it is a shared system it doesn't mean you can't give software access to hardware. C++ has the potential to give you lightening speeds in graphic work or by making use of the maths coprocessor or communications, or making direct use of some other part of the machine, or quite simply to optimise a function that in managed world would be a bottleneck.



What you want as a C++ programmer, if you are on a Windows machine, is to open your new projects with No Managed Code included. You want to break that managed link just so that you get more of the power of the PC working for you in your application.
green meklar
2012-01-19 18:40:45 UTC
A pointer IS a type of variable.



That said, the main use of pointers is for dynamic memory. You can order the computer to reserve a block of memory and have a pointer point to it so that you can use it; and these reservations can be done dynamically, based on what the program is doing. There are also other uses of pointers that you will find out later, they help with various data structures and whatnot.
?
2012-01-19 12:48:26 UTC
If you know that every variable is within a piece of memory in the RAM, the address is a handle to it.

Pointers are a means to access those handles and manipulate the contents within them.



If, lets say, you declared 3 variables of type int, then you could use a single pointer (which also has as an int pointer (or type-casted to int) ) and use that single pointer to manipulate any one of those int variables.

They are also a good means to manipulate arrays. You can have a pointer to a pointer as well, if you want to do some really tricky things.

There are pointers to functions as well.
anonymous
2012-01-19 11:39:01 UTC
Pointers are considered an advanced aspect of programming. It's really difficult to just give you a description in a nutshell.



Here's the official definition:



"Pointer is a programming language data type whose value refers directly to (or "points to") another value stored elsewhere in the computer memory using its address."



Here are layman terms:



Pointers let you skip around to other parts of your source code by pointing from one thing to another, and therefore, executing functions in the order you want, versus line by line.



Hope that helps or at least points you in the right direction.
Cubbi
2012-01-19 11:43:43 UTC
Raw ("C-style" or "naked" or "dumb") pointers aren't very useful unless you're implementing a low-level library. While you're new to C++, it is best to avoid them.



To list some of their actual uses:



The new-expression (e.g. "new Type(args)") always returns a (raw) pointer, so pointers must be used to track objects that have dynamic storage duration. Such pointers are usually wrapped in appropriate self-managing "smart" pointer types, such as std::auto_ptr or std::unique_ptr.



Pointers are used to express various forms of aggregating class relationships and various object ownership models (here both raw pointers and shared/weak/unique-ownership pointers are used, depending on class design)



Pointers are used to implement runtime polymorphism, e.g. when implementing a container of polymorphic objects. (references can be used for runtime polymorphism as well, but not when a container needs to be implemented)



Pointers can serve as "maybe'" types because they can point to an object or be null, although there are common library classes to do this explicitly.



Pointers can serve as rebindable references, which is sometimes quite useful e.g. when implementing balanced trees.



Pointers to functions may serve as delegates or callbacks, although lightweight function objects are more common in this role.



A lot of mixed C and C++ code uses pointers where C++ would use references (C has no concept of pass-by-reference, so it had to simulate it by passing pointers to functions). Also, a lot of C code uses pointers to refer to arrays and to iterate through arrays (C++ has vectors and strings instead, which can be referred to directly and which have dedicated iterator types).



This multitude of uses makes pointers confusing to learn.
pizarro
2016-12-03 17:36:13 UTC
once you're coding everywhere on the edge of any of those limits then i do now no longer decide to be the in effortless words that has to de-malicious utility your code. some element it incredibly is programmed with a repetition of code, be it nested circumstances, nested loops, assignments that exceeds the arbitrary form of 7, is in all probability badly written and there ought to decide to be a extra suited smart, extra suited concise way of writing the code which will make extra suited smart use of the language getting used and be extra suited powerful to execute and bigger readable. have relaxing.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...