what would I use pointers for?
I used to have a vague understanding of a pointer...
like,
*ptr is the value pointed to by the pointer,
ptr is the address the pointer is pointing to,
and &ptr is the address of the pointer itself?
or something?
the one example I have seen is putting an &argument into a function to make a reference/output argument, but I don't want to use output arguments anyways... what are other important uses for pointers in C++?

--edit--

oh, also.. Can I just drop hex values into my program?
Like, if I have an int containing the ASCII value of a character,
and I want to check if it is a numeral,
can I do something like if(charValue>0x29&&charValue<0x3A){ } ?

Recommended Answers

All 12 Replies

Do a google search for linked data structures (ie. linked lists, binary trees) and you'll discover a good use for pointers.

Okay, well I found an old book about C programming and it has linked lists in it... Would I use those in C++? What's a practical using them instead of classes or other structures?

Where else is a pointer useful?

Thanks for the help

I'm not going to enumerate every possible use I can think of. If you're having trouble thinking of ways that pointers are useful then either you don't understand them as well as you think, or you don't have enough experience programming to fully grasp the uses even if I do list them.

And yes, you can use linked lists in C++ too. :icon_rolleyes:

Pointers are very much in practical use . Since you have mentioned about C++ so i hope this small eg. will help you to realize the power of pointer . For implementing run time polymorphism you use pointers .

>For implementing run time polymorphism you use pointers .
Or references, but in reality references are just restricted pointers with a more convenient syntax.

Since I'm so nice (but not as nice as I used to be), I'll also mention that pointers are so useful, the concept has been adopted by iterators, which are used practically everywhere in the standard library of algorithms and containers.

I'll also link to this page, which is more of a what and how rather than where and when, but it might offer some insights you haven't reached yet.

Finally, I'm of the opinion that pointers are an intuitive thing, and if you don't have that intuition, you'll have a great deal more trouble with C and C++ than someone who intuitively "gets it". That's not to say that you should drop the language and start using Python or some other language that hides these details from you, rather that you'll have to work harder to achieve the same level of proficiency that those who naturally understand pointers.

Of course, it could also be that you've been brainwashed by the masses who insist that pointers are difficult. The concept is simple and the practice is simple. Any difficulty comes from the programmer thinking too hard and making it more difficult than it really is. In a way, a lot of people sabotage themselves by believing that something is difficult before learning enough to realize it's dead easy.

Do you understand the differences between storing stuff on the stack, and storing stuff on the heap?

"I'm not going to enumerate every possible use I can think of."
I'm not sure why you would number them, but, I just meant some of the main things that pointers would be used for, in most programs.

"And yes, you can use linked lists in C++ too."
I know you can use them, as any C++ compiler can compile a C program, I just didn't know if the implementation of classes and object oriented programming in C++ made them obsolete.

"Finally, I'm of the opinion that pointers are an intuitive thing, and if you don't have that intuition, you'll have a great deal more trouble with C and C++ than someone who intuitively "gets it". That's not to say that you should drop the language and start using Python or some other language that hides these details from you, rather that you'll have to work harder to achieve the same level of proficiency that those who naturally understand pointers."
You're definitely right about pointers being intuitive,
however maybe the lack of said intuition that you see in me could really just be that I am new to the language :)
Also, I'm moving from VB and assembly to C++, so obviously a lot of the concepts are going to be hard to grasp at first,
but I also write PHP which is in ways similar to C++ (more similar than VB is, anyway) so I'm just picking up the things that you must do in C++ (like allocating memory or using pointers, for example) that don't exist in PHP or VB.

"Do you understand the differences between storing stuff on the stack, and storing stuff on the heap? "
no,
but I know what the stack is.

ok im pretty new to programming and c++ but i will try to do my best.

if you declare an object on the stack, and your jumping around to different functions, that object is just being copied and passed around. when you declare a pointer and use the "new" keyword to create an object, you are creating a

a)object on the "heap" (just another area in memory)
b) a pointer that holds the memory address to that object.

the advantage is that you can pass that pointer around to different functions, and it will keep track of where to find that object.
So instead of making tons of copies of that object and allowing them to fall out of scope as you move around to different functions,
you are making one object, and passing around a pointer to allow functions to find it on the heap.
There is more too it than just that, but that is my noobish understanding.

ie. semi sudo code

Car myCar; //you declared a car on the stack

Car *myCar = new Car(); //you declared a pointer on the stack
called myCar, and a Car object on the heap.

now if you want to pass your car to another function
Garage *myGarage = new Garage(myCar);//create a garage and
//pass the memory address of your car.

you passed the memory address of the car object you created instead of creating a whole new copy of your car.
You are doing that because the stack is very dynamic, data is constantly being pushed on or popped off as you move through different functions, your objects can "live" on the heap and avoid going in and out of scope constatly

>I'm not sure why you would number them
I probably wouldn't number them, but you were entering into a disturbing pattern where I would end up listing them constantly:

You: "Can you tell me where pointers are useful?"
Me: "Linked data structures."
You: "You can tell me another place where pointers are useful?"

Clearly that would go on and on until you were satisfied, at the cost of my sanity.

>I just didn't know if the implementation of classes and object
>oriented programming in C++ made them obsolete.
Wrapping something in a class doesn't make it go away. You can have a linked list class, but it's still a linked list and quite likely will use pointers in the implementation. A class is there for notational convenience, it doesn't change how things work under the hood.

The only real difference between a linked list class and a C-style linked list library is how client code uses it, so suggesting that classes and object oriented programming make linked lists obsolete is nonsensical.

>Also, I'm moving from VB and assembly to C++, so obviously a lot
>of the concepts are going to be hard to grasp at first
Feh, if you know assembly then pointers should be a breeze. The instruction pointer and stack pointer are both prime examples of an address pointer and pointer arithmetic. You also know about indirection through effective addressing to offset a base address. Unless you're as new to assembly as you are to C++, I'd expect pointers to be the least of your worries because in assembly they're even more "in your face" than with C.

>ok im pretty new to programming and c++ but i will try to do my best.
Good start, but allow me to correct you on a few points by describing how a common compiler function call model works. I'll keep it simple (probably too simple for complete accuracy), but this should suffice to clear up a few things.

Functions work by creating a stack frame, where the return address and arguments are pushed onto the stack and then execution jumps to the first executable address in the function body. Note that when I say "pushed onto the stack", no extra memory is being allocated, the stack pointer is simply being adjusted to make a hole large enough for the argument type, then the value of the argument is copied into that hole.

Scoping is in place such that the arguments and any local variables are popped off of the stack before the function returns. Conversely, "popped off of the stack" means that destructors are called and then the stack pointer adjustment made when creating the stack frame is reversed.

Barring arrays, which have special rules in place, the argument is copied in toto onto the stack, just as you described. However, there are two facts that make your explanation somewhat incorrect.

  1. All function arguments are copied by value on the stack, even pointers.
  2. Pointers are not restricted to heap memory, they can point to any address, even one on the stack.

The parameter is a copy of the argument, which can be tested by printing the address of the parameter. The value of the parameter is the same value as the argument, which means that the contents not only are comparably equal, but has the same identity, even though the pointer holding that address is different:

#include <cstring>
#include <iostream>

void foo ( char *p )
{
  std::cout<< (void*)&p <<"->"<< (void*)p <<"->"<< p <<'\n';
}

int main()
{
  char buffer[] = "this is a test";
  char *a = buffer;       // On the stack
  char *b = new char[15]; // On the heap

  std::strcpy ( b, buffer );

  std::cout<< (void*)a <<"->"<< a <<'\n';
  std::cout<< (void*)b <<"->"<< b <<'\n';

  foo ( a );
  foo ( b );

  delete [] b;
}

In both cases (heap and stack) you can use a pointer to the memory and attain the performance benefits of passing around a smaller object on the stack.

Note that when the function returns, only p is popped off of the stack. a and b, and more importantly, buffer and the dynamic memory remain unchanged. The only scoping issue where the stack memory would be destroyed is if you want to leave the scope in which it's created. This is where using dynamic memory is good:

// BROKEN CODE
char *foo()
{
  char buffer[] = "this is a test";
  return buffer;
}

This will clearly cause problems because buffer is placed on the stack as a local variable, but when the function returns, that memory on the stack is reclaimed for other use. The solution, of course, is to use heap memory instead because it's on the heap and not bound by the limitations of scope:

char *foo()
{
  char *p = new char[15];

  std::strcpy ( p, "this is a test" );

  return p;
}

The memory pointed to by p will live until it's explicitly deleted, and as long as you have a pointer that points to it up to that point, all is well. The conclusion is that going down the scope tree, you don't have to worry about stack memory being reclaimed, but going up the scope tree, you do.

This gives you one big reason to use heap memory instead of stack memory: you're moving up the scope tree and need to retain a block of memory.

Another is available size. The stack is allocated to a process by the operating system on startup. However, you generally don't know how big the stack is, and it's possible to fill it up. That's where the heap comes in because it's a much larger pool (especially when you throw in virtual memory). However, for those reading this wondering why we don't always use the heap, allocating heap memory is a great deal slower than simply adjusting the stack pointer.

thanks... I figured most of this out with my book on C and a tutorial website though

So you have the fundamentals of pointers down... what part are you wondering about?

well, I sorta knew what they were I just had never used them in any application before, I'm just sorta picking C++ up part by part. I looked up dynamic memory allocating and figured out what the heap is, and that the new/new[]/delete/delete[] operators are the same as the whole malloc() set in C, which I read in my manual... Anyways I'm learning classes now, I'll probably return to pointers more in depth later.
Thanks for your help

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.