Usefulness of Pointers in C++?

  • C/C++
  • Thread starter MinusTheBear
  • Start date
  • Tags
    Pointers
In summary,The text essentially says that pointers are useful for allocating memory for arrays that you don't know the size of, and that they can be more efficient than using array indexing. However, every example given so far has been possible to code without pointers, and they also mention that pointers can be a source of errors.
  • #1
MinusTheBear
22
0
Hey everyone,

I'm currently going over a chapter on pointers for my 2nd programming course (no prior experience outside of class). I'm wondering what the usefulness of pointers is, other than if you need direct access to the memory location of a variable.

The text essentially says it's good for dynamically allocating memory for arrays that you don't know the size of. However, every example they've given so far, I am able to code another way without pointers. And it makes the code way easier to follow (in my opinion).

The only thing that I can think of is that it could potentially increase the efficiency of the code since you can delete the pointer when you're done with it and re-create it when you need it. However, isn't this essentially the same as a local variable just with a little more flexibility?

Currently it just seems like a more surefire way to end up with errors.
 
Technology news on Phys.org
  • #2
MinusTheBear said:
Hey everyone,

I'm currently going over a chapter on pointers for my 2nd programming course (no prior experience outside of class). I'm wondering what the usefulness of pointers is, other than if you need direct access to the memory location of a variable.

The text essentially says it's good for dynamically allocating memory for arrays that you don't know the size of. However, every example they've given so far, I am able to code another way without pointers. And it makes the code way easier to follow (in my opinion).

The only thing that I can think of is that it could potentially increase the efficiency of the code since you can delete the pointer when you're done with it and re-create it when you need it. However, isn't this essentially the same as a local variable just with a little more flexibility?

Currently it just seems like a more surefire way to end up with errors.
Take a look at Linked Lists. That's one place where pointers make a lot of sense, IMO.
 
  • #3
MinusTheBear said:
The text essentially says it's good for dynamically allocating memory for arrays that you don't know the size of.
In the case of C, you can use something like int *ptr2array = malloc(count * sizeof(int) ) to allocate a large array from the heap. If you have an array of objects that you need to sort, it may be faster to create an array of pointers to objects and sort the array of pointers. The objects could be lines of text from a file read into memory as a single block of memory.
 
  • #4
A pointer is a variable containing the address of another variable. Pointers allow you to refer to the same space in memory from multiple locations (they're not copies of a variable) and each of the locations could have a different representation (data structures) of the memory in that same space. You can also have function pointers where the variable contains the address of a program function can be executed via the function pointer.

"It's easier to give someone an address to your home than to give a copy of your home to everyone." so everything actually uses pointers but C/C++ just exposes them to the programmer rather than hiding them.

"surefire way to end up with errors"
Yes, If you don't know exactly why you're using pointers, you shouldn't use them.
 
  • #5
One thing about C/C++ pointers are that they are datatype oriented.

By that I mean a char pointer when incrementing it will add one causing the pointer the reference the next byte whereas an int pointer will increment by two bytes (for 16-bit ints) and a double pointer will increment by 8 bytes...

Here's some more info on pointers which are everywhere in C/C++ and are actually favored over array indexing in many cases.

https://www.tutorialspoint.com/cprogramming/c_pointers.htm
 
  • #6
MinusTheBear said:
Hey everyone,

I'm currently going over a chapter on pointers for my 2nd programming course (no prior experience outside of class). I'm wondering what the usefulness of pointers is, other than if you need direct access to the memory location of a variable.

The text essentially says it's good for dynamically allocating memory for arrays that you don't know the size of. However, every example they've given so far, I am able to code another way without pointers. And it makes the code way easier to follow (in my opinion).

The only thing that I can think of is that it could potentially increase the efficiency of the code since you can delete the pointer when you're done with it and re-create it when you need it. However, isn't this essentially the same as a local variable just with a little more flexibility?

Currently it just seems like a more surefire way to end up with errors.

I'll talk about pointers in C but the same concepts expand for C++ giving a lot more power, given the existence of objects.

Essentially, pointers are variables whose values are memory addresses. So, in contrast to a normal variable that contains a specific value, a pointer contains an address of a variable that contains a specific value. So, a pointer indirectly references a value.

Pointers enable programs to simulate call-by-reference and to create and manipulate dynamic data structures i.e structures that their size is changed at execution time. Such structures are linked lists, queues, stacks and trees. You can't allocate memory beforehand for data structures that will grow or shrink at execution time, without doing dynamic allocation of memory through pointers.

I'll also give you a reference for the concepts of pointers and their use, "Pointers and Memory" from Stanford CS Education Library by Nick Parlante.
 
  • #7
MinusTheBear said:
The text essentially says it's good for dynamically allocating memory for arrays that you don't know the size of. However, every example they've given so far, I am able to code another way without pointers. And it makes the code way easier to follow (in my opinion).
If you need to allocate an array whose size isn't known at compile time, you can allocate space on the heap dynamically (i.e., at run time) using malloc(). I'm thinking in terms of C here.

Sure it's more complicated, but it allows you to do something that you couldn't otherwise do -- determine during a program's run exactly the size of the array you need. Otherwise, using statically declared arrays (arrays declared at compile time), you have to declare the array to be large enough to hold as much data as you think might be needed. This means that much of the time your array will be larger than what you need, wasting memory, and too small if you guessed wrong on the maximum size you need.

nsaspook said:
A pointer is a variable containing the address of another variable.
The address is not necessarily another variable. You can have a pointer to a function of a specific type, which is the way qsort() works with its parameter that is a pointer to a comparison function. Or the pointer can hold the address of some location in memory that has no identifier associated with it.

jedishrfu said:
One thing about C/C++ pointers are that they are datatype oriented.

By that I mean a char pointer when incrementing it will add one causing the pointer the reference the next byte whereas an int pointer will increment by two bytes (for 16-bit ints) and a double pointer will increment by 8 bytes...
All true, but a pointer can be cast to a pointer of a different type. Also, most C/C++ compilers these days consider the int type to be 4 bytes, not 2. That change happened along about 1997 or so, causing me some confusion, as I was used to ints being two bytes.
 
  • Like
Likes jedishrfu and QuantumQuest
  • #8
MinusTheBear said:
The text essentially says it's good for dynamically allocating memory for arrays that you don't know the size of. However, every example they've given so far, I am able to code another way without pointers.
Let me guess... using std::vector?
 
  • #9
Thanks @Mark44 for the update. In 1997 or so was the I jumped on the Java train with version1.1 and haven't looked back.
 
  • #10
Heh, I've been using C++ since 1985. (Anyone here remember cfront 1.0?) Anyway, there's an old computer science saying:

Every software design problem is solved by introducing one more level of indirection.

When you can understand that, Grasshopper, you will have learned (the relevance of pointers). :wink: :biggrin:
 
  • #11
MinusTheBear said:
Hey everyone,

I'm currently going over a chapter on pointers for my 2nd programming course (no prior experience outside of class). I'm wondering what the usefulness of pointers is, other than if you need direct access to the memory location of a variable.

The text essentially says it's good for dynamically allocating memory for arrays that you don't know the size of. However, every example they've given so far, I am able to code another way without pointers. And it makes the code way easier to follow (in my opinion).

The only thing that I can think of is that it could potentially increase the efficiency of the code since you can delete the pointer when you're done with it and re-create it when you need it. However, isn't this essentially the same as a local variable just with a little more flexibility?

Currently it just seems like a more surefire way to end up with errors.

You have good instincts. Sure pointers can be used to support a lot of use cases, but hardly any of them require the use of raw pointers. And it's the general consensus of the C++ creators and communities that raw pointers should be avoided as much as possible. Like you say, almost all of their use cases can be replaced by safer and more idiomatic C++ alternatives. In fact, most C and C++ programs are plagued by memory leaks and security issues and various bugs because of faulty use of raw pointers. But it's not just memory leaks, improper casting is also a problem. Their use is sometimes a way to get around type safety, or to implement a hackish and potential unsafe or hard to understand way to accomplish something.

In good idiomatic C++, you can almost virtually eliminate the possibility of memory leaks in the code you have written (no telling about its dependencies) of such problems. I am quite sure no memory leaks have been introduced by my code in the several years since I started writing proper C++ code.

Of course for certain reused data structures it could be preferable to just use raw pointers rather than the alternative of existing data structures that encapsulate them. But such use cases should ideally be limited to fairly small encapsulated modular classes or structs that are not constantly being modified and which are evaluated by someone compitent. But at the very least, you should limit calls to new only inside a constructor and to always make sure to call delete in the destructor. This both guarantees the memory will be freed when the object goes out of scope, and it eliminates the need to search though your code aimlessly trying to keep track of where things are being allocated and allocated. It would also be good practice to initialize pointers to 0 if you are scattering new and delete all around, since deleting a null pointer won't cause any problem (although if this is happening it's a sign your code is messed up anyways).

Otherwise the main justifiable use case for pointers is to support polymorphism (inheritance). Of course you can often still use smart pointers. I don't think you shouldn't just go filling a vector with dynamically allocated raw, owning pointers for example.

At the basic level, choose pass by reference over pass by pointer, choose functors or lambdas over function pointers, choose vectors or smart pointers of other encapsulations/classes over using raw pointers to dynamically allocated objects, and in general whenever you find yourself using a raw pointer, give a second thought about whether it's really the best approach.
 
Last edited:
  • #12
Jarvis323 said:
You have good instincts. Sure pointers can be used to support a lot of use cases, but hardly any of them require the use of raw pointers. And it's the general consensus of the C++ creators and communities that raw pointers should be avoided as much as possible.
Those are good points, but for the OP, who is just starting out, I believe that it's important to understand how pointers work. Whether they should be used in a particular case is a separate issue.
 
  • Like
Likes QuantumQuest
  • #13
Pointers are important when you want to have multiple threads or objects all working with the same information. Here is a time that I use pointers extensively: option pools. I often have classes that can work in several different ways, and instead of injecting a single strategy in it, which requires mallocs and frees when changing, I create member objects and create a pointer called m_active, which I simply point to whichever strategy I want.
 
  • #14
Pointer is also usefull for some scabrous trick in template programing, and for inheritance.
 
  • #16
Scabrous is an english word for risky, dangerous, or complex, it's not the name of a method.
 
  • Like
Likes jedishrfu
  • #17
I think he's referring to something like this.

C:
struct parent {
    virtual ~parent(){}
    virtual void step(void){}
};
struct child : public parent {
    virtual void step(void){}
};

std::vector<parent *> container;
container.push_back(new parent);
container.push_back(new child);
container.push_back(new parent);

std::vector<parent *>::iterator i = container.begin();
std::vector<parent *>::iterator e = container.end();
for (; i != e; ++i){
    if (i -> step == child::step){  //Should always work, but scary code
       std::cout << "Hacky way to check type revealed a child" << std::endl;
    }
}

Polymorphic objects have hidden member variables that point to sections of code. These are called the vtable.
 
Last edited:
  • Like
Likes QuantumQuest and jedishrfu
  • #18
A very simple example is to make a vector of box to put everything you want inside.

//Useless Parent
class parent
{
}

// But Template Child
template<class T>
class child : public parent
{
public :
child(T * p):my_class(p){}

private :
T * my_class;
}

std::vector<parent *> v;
v.push_back(child(WhatYouWant));
...

This example go against the inheritage principle but can be usefull in some configuration.
 

1. How are pointers useful in C++?

Pointers are useful in C++ because they allow for dynamic memory allocation, which means that memory can be allocated and deallocated at runtime rather than being fixed at compile time. This allows for more efficient use of memory and can help improve the performance of a program.

2. How do pointers make C++ more powerful?

Pointers make C++ more powerful because they allow for indirect access to memory locations, which means that data can be manipulated and shared between different parts of a program. This can help improve the flexibility and functionality of a program.

3. What is the difference between pointers and variables in C++?

Pointers and variables both store data, but they differ in how they store and access that data. Variables store data directly, while pointers store the memory address of where the data is stored. Pointers also allow for indirect access to data, while variables can only access data directly.

4. Can pointers be used for more than just dynamic memory allocation?

Yes, pointers can be used for more than just dynamic memory allocation. They can also be used to create data structures such as linked lists and trees, and can be used to pass data and functions as parameters to other functions. Pointers are also essential for implementing polymorphism in C++.

5. Are there any drawbacks to using pointers in C++?

While pointers can be very useful, they can also introduce some challenges and potential errors in a program. For example, if a pointer is not properly initialized or is pointing to an incorrect memory address, it can lead to unexpected behavior or even crashes. Additionally, using pointers can make code more complex and difficult to debug.

Similar threads

  • Programming and Computer Science
Replies
17
Views
1K
  • Programming and Computer Science
Replies
3
Views
734
  • Programming and Computer Science
Replies
19
Views
1K
  • Programming and Computer Science
Replies
5
Views
885
  • Programming and Computer Science
2
Replies
40
Views
2K
  • Programming and Computer Science
Replies
19
Views
2K
  • Programming and Computer Science
Replies
23
Views
1K
  • Programming and Computer Science
Replies
5
Views
820
  • Programming and Computer Science
4
Replies
118
Views
6K
  • Engineering and Comp Sci Homework Help
Replies
17
Views
1K
Back
Top