# C++ Pointers doubt

• Comp Sci
Can anyone help me understand the basic use of pointers.
I am aware of pointers,yet I feel that a program can be made more
easier without using a pointer.

My basic dout is that can pointers be used to save memory by dynamic declaration of variables.
I thought over it but found that using ptr in programs of my level is useless.

I have just begun with programming and not yet started with classes,ie OOP.
Could anyone suggest me some good programs.

chroot
Staff Emeritus
Gold Member
Many programs can indeed be written without pointers.

There are only a few instances where pointers become "necessary" for reasons of efficiency:

1) When you need to refer to the same large piece of data in many different places in the code.

2) When you need to allocate memory dynamically, and you don't know a priori what the address of that memory will be.

- Warren

Can you give me an example where I need to use pointer
Just the example without any code.

from my experiance these few instances occure quite often.

for example - binary trees, they are very important.. search bsp trees, for game use.
and linked lists are a necessity in database hendling...

Last edited:
Coding most data structures where the # of objects is large and varies constantly. Also if your structs/classes are large in memory and you only want one instance of the object but many such objects and have many manipulations to do on those objects like in Graph Theory Or anything that uses graph theory like neural nets. Another example is from fargoth about games, eg player or agent/ai entities...infact all entities in a game.

My basic doubt is that can pointers be used to save memory by dynamic declaration of variables.
I thought over it but found that using ptr in programs of my level is useless.

Yeah your correct in that pointers can make allocating memory more efficient, because you can decide at runtime what size a given field/variable needs to be rather than allocating a chunk at compile time. This is really something thats important in larger projects, but for simple low performance applications you can do without, however if your learning ( say from a text and practicing some programs ) then its really a good idea to get used to using them effectivley rather than opting for the easier route.

The main reason beginners find pointers so difficult is that their use is more abstract than lets say the use of an array. Their very abstract nature though gives the user great power. For instance, one could set a pointer to a memory location within a hardware register (assuming the OS will let you). Then you can pass that pointer down a chain of functions. Each of the functions will then have access to that register through the abstration of the pointer. The functions don't even need to know what the pointer is pointing at or anything about it.

Some languages such as Java don't have pointers. Java was made to be called by web pages. As such, pointers would allow hackers to create programs that could access your computer memories. This is dangerous so the designers of the language simply left it out. This reduces the power of the language, but gives it the safety needed to create applets.

chroot
Staff Emeritus
Gold Member
interested_learner,

The reason Java lacks pointers is because everything in the language is passed by reference. The designers of the language chose this approach because it makes programming easier and less prone to error.

Passing by reference is a higher-level, abstracted form of using a pointer. There are many ways to protect memory access even with the use of pointers, and all modern operating systems use such protection.

- Warren

From my experience with pointers, it creates alot of problems when you dont know how to handle them properly..... ie. dangling pointers and so on. And passing by reference in JAVA works alot better for me and is easier to understand.........each to their own i suppose...

I also doubt one more yhing that while declaring a pointer we allocate a memory location i.e we allocate the same amount of memory as the one to which yhe pointer points .
So this means that we initially allocate memory for the pointer then again go for dynamic declaration of another variable.

so if suppose we are utilising more memory than we are supposed to.
Please correct me if i am going wrong anywhere in my logic.

jtbell
Mentor
Also note that the C++ standard library provides container objects that allow the programmer to avoid using raw pointers in many situations that would otherwise require them.

For example, in C and in C-style programming in C++, when you don't know the required size of an array at compile time, you have to allocate it dynamically. Also if you want to change the size of an array while the program is running, you have to allocate it dynamically. Instead of that, in C++ you can use the 'vector' data type which behaves sort of like a simple array that you can resize by using a member function. It actually implements this internally using a dynamically allocated array, but it hides all the pointer management from you, and you never deal with the pointer directly (it's "private" to the vector).

Similarly, the 'string' data type allows you to dispense with char*.

There's also a 'list' container which basically encapsulates a doubly-linked list (with forward and backward pointers), a 'map' container which usually uses a tree structure internally, etc.

I am now clear that we can save memory by dynamic allocation of memory by the example of array declaration.

I would like to know more about 'vector' data type .
Can you please send me a link or suggest any source to get more knowledge on C++.

Last edited:
jtbell
Mentor
I can't help you with online sources because I'm more comfortable with using books to learn a subject as complex and as structured as programming. For people who already know a bit about programming, I highly recommend "Accelerated C++" by Koenig and Moo. It's a thoroughly modern treatment of C++ that uses vectors instead of arrays, strings instead of char*, etc. I also recommend it to people who know quite a bit of C++ already, but haven't worked much with the containers in the standard library.

Most other C++ books and tutorials show you the "old fashioned" way to do things first. By the time you get to the nifty things in the standard library, which aren't really that hard to use, you've formed habits that are hard to break.

Here's a quick sample of what vectors can do:

Code:
//  This is a quick demonstration of the 'vector' data type, showing
//  a couple of reasons why it's nicer than a plain old array.

#include <iostream>
#include <string>
#include <vector>

using namespace std;

int main ()
{
// Create this vector with a specific size and fill each slot
// individually.

vector<string> myStrings(7);

myStrings[0] = "Hi";
myStrings[1] = "I";
myStrings[2] = "am";
myStrings[3] = "a";
myStrings[4] = "vector";
myStrings[5] = "of";
myStrings[6] = "strings";

// Display the contents of the vector.  Note that a vector can tell you
// how big it is, so you don't have to keep track of the size (7)
// separately.

for (int k = 0; k < myStrings.size(); ++k)
{
cout << "String #" << k << ": " << myStrings[k] << endl;
}

// Create this vector with initial size zero, and let it grow to
// accommodate the data

vector<string> moreStrings;

cout << "Enter a series of strings, one per line;\n"
<< "enter an empty line to finish:" << endl;

// Read strings one at a time.  They can contain spaces because
// we're reading line by line using getline().

string newString;
while (getline (cin, newString) && newString != "")
{
//  Append each new string to the end of the vector.
//  The vector automatically grows to accommodate the data.

moreStrings.push_back (newString);
}

// Display the contents of the vector.  As we are writing this program,
// we don't know how big the vector will be at this point, but
// the vector can tell us its current size anyway.

for (int k = 0; k < moreStrings.size(); ++k)
{
cout << "String #" << k << ": " << moreStrings[k] << endl;
}

return 0;
}

I've tested this program, so you should be able to just copy and paste and compile and run it.

Homework: try to rewrite this program using arrays and pointers instead of vectors, and char* instead of strings, while still allowing the user to enter any number of strings, of any length!

Last edited:
scorpion: search in google for STL(standard template library)...i would give you the google site but my computer is having problems, nvm here is the list