C++ Pointers: Get Help Understanding Basics & Memory Savings

In summary, pointers can be used to save memory by dynamically allocating memory, but they can also be dangerous if not used correctly.
  • #1
scorpion
8
0
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.
 
Physics news on Phys.org
  • #2
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
 
  • #3
Can you give me an example where I need to use pointer
Just the example without any code.
 
  • #4
from my experience these few instances occur 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:
  • #5
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.
 
  • #6
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 that's 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.
 
  • #7
The main reason beginners find pointers so difficult is that their use is more abstract than let's 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.
 
  • #8
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
 
  • #9
From my experience with pointers, it creates a lot of problems when you don't know how to handle them properly... ie. dangling pointers and so on. And passing by reference in JAVA works a lot better for me and is easier to understand...each to their own i suppose...
 
  • #10
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.
 
  • #11
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.
 
  • #12
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:
  • #13
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:
  • #14
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

"http://www.google.ca/search?client=firefox-a&rls=org.mozilla%3Aen-US%3Aofficial_s&hl=en&q=STL&meta=&btnG=Google+Search"

Does Java have the problem of passing in the entire variable(by reference not by copy) through the parameter list of a function? Does reference variables declared in the code-body work in Java same way it does in C++, that is you can only initialize it only once(CType &x; x=y; //where y defined somewhere else, and x cannot equal anything else)...if so then i can see this as an advantage for C++, because if your searching for an object in an array(eg. nearest neighbour) you can store by pointer without having to copy all the values of that class. If Java doesn't allow ptrs then you would have to copy the class(unless of courses the reference usage isn't the same as in C++).
 

1. What are pointers in C++?

Pointers in C++ are variables that store the memory address of another variable. They are used to indirectly access and manipulate the value of the variable they point to.

2. How do pointers help with memory savings in C++?

Pointers help with memory savings in C++ by allowing for the dynamic allocation of memory. This means that memory can be allocated at run-time, which can save memory space compared to statically allocating memory.

3. How do I declare and initialize a pointer in C++?

To declare a pointer in C++, use the asterisk (*) symbol followed by the name of the pointer variable. To initialize a pointer, assign it the memory address of the variable it will point to using the ampersand (&) operator.

4. What is the difference between a null pointer and a void pointer in C++?

A null pointer in C++ is a pointer that does not point to any memory address. This can be used to indicate that a pointer is not currently pointing to a valid object. A void pointer, on the other hand, is a generic pointer type that can point to any data type.

5. How do I use pointers to pass arguments to functions in C++?

To pass arguments by pointer in C++, the function parameters should be declared as pointers. The memory address of the arguments can then be passed as the argument when calling the function. This allows for the function to directly modify the value of the argument in the memory location it points to.

Similar threads

  • Engineering and Comp Sci Homework Help
Replies
17
Views
1K
  • Programming and Computer Science
Replies
17
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
2
Views
875
  • Engineering and Comp Sci Homework Help
Replies
7
Views
1K
  • Programming and Computer Science
Replies
19
Views
2K
  • Programming and Computer Science
Replies
5
Views
831
  • Programming and Computer Science
2
Replies
40
Views
2K
  • Programming and Computer Science
Replies
12
Views
994
  • Engineering and Comp Sci Homework Help
Replies
4
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
12
Views
2K
Back
Top