Jump to content

  • Log In with Google      Sign In   
  • Create Account


use of pointers

  • You cannot reply to this topic
13 replies to this topic

#1 RaoulJWZ   Members   -  Reputation: 359

Like
0Likes
Like

Posted Yesterday, 10:13 AM

Hello everyone,

 

right now i'm reading a book about c++.

It explaines very well how to use pointers, but it's not very clear why

to use them and why they are so handy. Could you tell me that

 

thanks in advance.



Sponsor:

#2 KulSeran   Members   -  Reputation: 2199

Like
7Likes
Like

Posted Yesterday, 10:48 AM

Probably because nearly everything ends up being a pointer at some point.  Memory can be thought of as a bunch of numbered boxes arranged in order.  You might call 4 of those boxes "x" when you define "int x = 5;" but they're still numbered and the compiler still keeps track of where "x" is in terms of the numbered boxes.  Because of that, you can type "int *pointerX = &x;" to get that information for yourself.  So, why would you?

 

To modify something in another scope.

void bar(int &n) {
  n = 7;
}

void baz(int *n) {
  *n = 8;
}

void foo() {
  int x = 5;
  std::cout << x << std::endl; // 5
  bar(x);
  std::cout << x << std::endl; // 7
  baz(&x);
  std::cout << x << std::endl; // 8
}

To keep track of things not allocated on the stack.  X in the example above is stack allocated.  But to hold larger values, you need to get memory from the OS using functions like malloc/free and new/delete.  This opens up the world of dynamic allocation.  It can be tricky, and you'd generally want to use tools like std::list, std::vector, std::map to handle this for you.

void printArray(int *n, int size) {
  for (int i = 0; i < size; ++I) {
    std::cout << n[i] << ", ";
  }
}

void foo() {
  int count = 0;
  std::cout << "how many numbers to generate" << std::endl;
  std::cin >> count;
  // this won't work.  Since count isn't known at compile time.
  // int x[count];
  // but this will:
  int *x = new int[count];
  for (int i = 0; i < count; ++I) {
    x[i] = rand();
  }
  printArray(x, count);
  // and you have to clean it up afterwords.
  delete[] x;
}

But one of the key comments there is "known at compile time".  If you want to have a max of 32 players in a game, that can be hard-coded and the compiler can know about it.  But if you want the max player count to be read in from a config file, so that people can increase it later if their machines are powerful enough, then the compiler can't know about it.  When the compiler can't know about the count of objects, you're into the realm of needing to dynamically allocate objects which at some point results in pointers to memory being created.



#3 Glass_Knife   Moderators   -  Reputation: 3522

Like
5Likes
Like

Posted Yesterday, 11:19 AM

I've been wondering about this myself.  From the perspective of someone teaching C++, it can be difficult to explain the difference between a variable, a reference, and a pointer.

 

I have not found a good example.  Using the analogy of little boxes is good, but it still fails to capture the concept.  

 

I suspect that using a pointer or a reference to an object is understandable when the student understands that all items passed to/from functions are copied.  It is much better to copy a 32bit pointer or reference to an object that to copy the object.

 

And as KulSeran pointed out, if you need to allocate memory at run time, you'll get a pointer, so you need to understand how they work.  But for me, I still feel like something is missing capturing the difference between a reference and a pointer.  

 

C++ references have two properties:

  • They always point to the same object.
  • They can not be 0.

Pointers are the opposite:

  • They can point to different objects.
  • They can be 0.

But I have been unable to explain this so that someone new to the language can remember or understand the significance.  

 

Any thoughts which might help me and the OP?


Edited by Glass_Knife, Yesterday, 11:23 AM.

I think, therefore I am. I think? - "George Carlin"
Indie Game Programming

#4 JonathanCCC   Members   -  Reputation: 150

Like
1Likes
Like

Posted Yesterday, 11:30 AM

A reference must be initialized to point to something straight away and cannot be re-assigned to point to something else, unlike a pointer.

 

So it's good practice to use references over pointers where possible to avoid bugs and errors.


Edited by JonathanCCC, Yesterday, 11:31 AM.


#5 Andy Gainey   Members   -  Reputation: 1870

Like
6Likes
Like

Posted Yesterday, 11:32 AM

I think that for a person just learning to code, the focus should not be about the technical aspects of pointers, and how they differ from C++ references technically.  Instead, the focus should be on the high-level concept of references generally, abstracted away from C++ specifics.  Pointers just happen to be a somewhat low-level way to implement and express references.  So the question for a new programmer really becomes, "What's the use of references of any form?"

 

The general use of references are to provide a way for one piece of data to refer another piece of data by identity, not by value.  So that if the data that is referenced changes its value, the data that refers to it will be able to access the new value, rather than simply being left with a copy of the old value.

 

References in general (and as a consequence pointers also) make a whole lot more sense once you get into the computer science topic of data structures and algorithms.  Which I would strongly suggest any beginning programmer do as soon as they have a working grasp of basic programming concepts (variables, conditions, loops, simple input/output).  Data structures and algorithms sort of form the foundation of all computer science and good software engineering, in my opinion.  That, and I just find it to be a fascinating topic to explore, even now after two decades of programming.

 

When you begin studying the classic data structures like linked lists, trees, and hash tables, as well as the algorithms associated with them, such as searching for an item, sorting all items, or inserting and removing items, you'll really begin to appreciate how essential references are to programming.

 

For someone coming from another language that doesn't support pointers, the technical details do become more important, since they are likely to already know about data structures and the general uses of references.  In that case, I like to simply think of pointers as integers, and the computer's memory as one gigantic array.  The pointers just index individual elements of the array, and now I have a whole bunch more power and responsibility to manage these element references however I want.


Edited by Andy Gainey, Yesterday, 11:34 AM.


"We should have a great fewer disputes in the world if words were taken for what they are, the signs of our ideas only, and not for things themselves." - John Locke

#6 StaticPoof   Members   -  Reputation: 217

Like
3Likes
Like

Posted Yesterday, 01:43 PM

Try to think of pointers as street addresses.  Its a lot faster and more efficient to say I live at "101 binary street" than it would be to grab your actual house and say I live here.



#7 rip-off   Moderators   -  Reputation: 7719

Like
3Likes
Like

Posted Yesterday, 03:56 PM

Here are common reasons why people use pointers:

 

0) A particular object or array is large, and they don't want to incur a copy of it when passing to a function. Passing a pointer is small (typically four or eight bytes), versus copying potentially thousands or millions of elements in an array.

 

Note: C++ provides references for this.

 

1) The programmer wishes to add an optional parameter to a function. If the parameter is not important, the programmer will pass a nullptr. Otherwise, they pass the address of an interesting object. The function can test if the pointer is null before using it.

 

2) The programmer wishes an object to live beyond the scope it is created in. Typical C++ objects live in a given scope, and can only be copied outside that scope. By dynamically allocating the object and storing a pointer to it, the original object can live longer than its scope and can be deleted later. An example in a game is a bullet, there might be a shoot() function, but the bullet should live until it hits something, not be destroyed at the end of the function.

 

Note: modern C++ recommends using smart pointers for allocating and managing the ownership of such objects.

 

3) The programmer has a rich ownership convention, where raw pointers convey the concept of "this object does not own the other object". Care must be taken with this approach to avoid dangling pointers. A possible alternative is a "weak pointer". An example in a game might be an AI object's current target.

 

4) Interacting with C style APIs. Some APIs pre-date C++, or otherwise are written in a rather simple fashion (e.g. for crossing DLL boundaries). In this case you might be forced to deal with these pointers. An example in a game might be the SDL library, which returns the "screen" surface as a raw pointer from SDL_SetVideoMode().

 

Note: Modern C++ style recommends "wrapping" the code that deals with such objects to some degree, at the very least using smart pointers to manage their lifecycle.



#8 RaoulJWZ   Members   -  Reputation: 359

Like
0Likes
Like

Posted Yesterday, 04:02 PM

okay thanks everyone, i understand it way better now!



#9 Glass_Knife   Moderators   -  Reputation: 3522

Like
1Likes
Like

Posted Yesterday, 04:08 PM

Can I ask, for the education aspect, what made the light bulb go on?


I think, therefore I am. I think? - "George Carlin"
Indie Game Programming

#10 RaoulJWZ   Members   -  Reputation: 359

Like
2Likes
Like

Posted Yesterday, 04:20 PM

Well, all of the explainations pushed me more and more in the right direction (even staticPoof's :D),

There are two reactions who helped the most: The one from Andy Gainey and rip-off. 

For me these two reactions are clear and easy to understand, while english isn't my first language.

 

I hoped i answered the question with this, otherwise you just have to say it.

 

thanks again!



#11 Lactose!   GDNet+   -  Reputation: 2557

Like
1Likes
Like

Posted Yesterday, 05:50 PM

I also remember pointers clicking more in my mind when I thought them as addresses or directions for an object.

I thought about data types as e.g. boxes, and pointers as a paper with the directions to the box on it.

int myInt;

--> an int sized box with myInt written on it. int sized because it needs to be big enough to store whatever int I want to put in it.

 

int *myIntPointer = &myInt;

--> a piece of paper saying "the box in the kitchen on the top shelf".

 

Somewhat unrelated, hovering the "pointers" tag of this thread gives some fairly entertaining suggestions.



#12 frob   Moderators   -  Reputation: 19040

Like
3Likes
Like

Posted Yesterday, 07:11 PM


There are two reactions who helped the most: The one from Andy Gainey and rip-off. 
For me these two reactions are clear and easy to understand, while english isn't my first language.

 

That is my normally preferred explanation as well:

 

Try to think of pointers as street addresses.  Its a lot faster and more efficient to say I live at "101 binary street" than it would be to grab your actual house and say I live here.

 

 

You can either refer to the address, or you can chose that every time you refer to it you build a clone of the entire house, clone every item in the house, exactly duplicate the house in every aspect, then use the clone.

 

 

A pointer is just the address.  It is a scrap of paper with an address.  It can have a nonsense address, or even a blank address on the paper.

 

A reference is somebody saying "This is an object's home". It cannot be blank since that would make the object homeless. It cannot be modified, since the home will remain at that location.


Check out my personal indie blog at bryanwagstaff.com.

#13 HScottH   Members   -  Reputation: 448

Like
0Likes
Like

Posted Today, 12:06 AM

To not understand the utility of pointers is to not understand the language.  A much older and wiser engineer than myself once said something that I immediately understood and knew to be true: to be a real black-belt with any technological level, you must know the one beneath it.

 

To understand how to really use C or C++, you need some Assembly experience.  Not a lot, you don't need to be a pro, but this will show you what the machine is doing and how, and you will suddenly understand everything in C and C++ intuitively--and you'll be damn good at it too!

 

The good thing in that all modern C/C++ compilers support inline assembly, so you don't need new tools, just google "x86 assembly tutorial" and spend an evening or two doing some ultra-low level coding :-)



#14 tonemgub   Members   -  Reputation: 647

Like
0Likes
Like

Posted Today, 01:55 AM

A pointer is just 4 bytes (or 8 bytes in 64-bit), whereas the data it points to might be in the order of megabytes... Passing the pointer to the data around where it's needed is obviously faster than passing around the whole data.

 

Funny analogy: if you want to tell someone where you live, you don't just get a crane to lift your house and bring it to them to show them you live in that house... you just give them your address.







PARTNERS