Jump to content

Pointer Question


CoolPenguin
 Share

Recommended Posts

I'm just learning C++, and I have gotten to a chapter on Pointers in my C++ tutorial. I understand a pointer "points" to a memory address, and you can point to a variable's memory address and assign the address values, but what is the point? (No pun intended ^_^) I mean, why not just call the variable itself?

Look at this code:

#include <iostream>
using namespace std;

int main ()
{
  int z = 5;
  int * j;
  j = &z;
  cout << "The result is " << *j;
  return 0;
}

it is the same result as:

#include <iostream>
using namespace std;

int main ()
{
  int z = 5;
  cout << "The result is " << z;
  return 0;
}

I'm a little confused on the purpose of a pointer. Is it used for something that I might find useful later on in my tutorial? Right now it seems like a waste of code =\ Sorry if I sound a little stubborn.

Link to comment
Share on other sites

I'm no C expert by any means, but consider passing strings and data structures to functions. It is much more efficient to pass a pointer to the actual data of the string or structure in memory than to pass all of the data. Speaking of integers in your example, no it doesn't really make a difference since the size of the data is the same (32 bits).

Link to comment
Share on other sites

It comes down to working with memory by value or by reference (pointer). If you have a very large data structure that you want pass to a function, is it better to pass by value (which you can't change) or pass by reference - (which you can change). Side note - when you pass a param to a function it makes a copy of it within the function and destroys the copy after the end of the function.

Also if you want to get some dynamic memory, how are you going to hold it.

There are many many uses for pointers and soon you will see the use for a pointer to a pointer - that will spin you out!

Post your code because code says more then your words can. SciTe Debug mode - it's magic: #AutoIt3Wrapper_run_debug_mode=Y. Use Opt("MustDeclareVars", 1)[topic="84960"]Brett F's Learning To Script with AutoIt V3[/topic][topic="21048"]Valuater's AutoIt 1-2-3, Class... is now in Session[/topic]Contribution: [topic="87994"]Get SVN Rev Number[/topic], [topic="93527"]Control Handle under mouse[/topic], [topic="91966"]A Presentation using AutoIt[/topic], [topic="112756"]Log ConsoleWrite output in Scite[/topic]

Link to comment
Share on other sites

Can't you use pointers to point to functions? This seems like something that could be used (and abused) that exhibits something nice about pointers. Also, I found that learning a bit of C++, especially about pointers, really helps you understand a lot more of what goes on under the hood in other languages.

Link to comment
Share on other sites

Pointers can be used for all interesting things as mentioned here. As interacted there are many ways that they can abused - non of which we can talk about here.

Pointer to a reference, I have never had to do that. Have worked with both (as I recall, a reference is a pointer to a pointer with the work taken out). I cannot think of a need to have a pointer to a reference. Why not pass the reference by value?

Post your code because code says more then your words can. SciTe Debug mode - it's magic: #AutoIt3Wrapper_run_debug_mode=Y. Use Opt("MustDeclareVars", 1)[topic="84960"]Brett F's Learning To Script with AutoIt V3[/topic][topic="21048"]Valuater's AutoIt 1-2-3, Class... is now in Session[/topic]Contribution: [topic="87994"]Get SVN Rev Number[/topic], [topic="93527"]Control Handle under mouse[/topic], [topic="91966"]A Presentation using AutoIt[/topic], [topic="112756"]Log ConsoleWrite output in Scite[/topic]

Link to comment
Share on other sites

It comes down to working with memory by value or by reference (pointer).

References are not pointers. It's important when talking about C++ to distinguish between references and pointers because both are available in the language and both are different things.

If you have a very large data structure that you want pass to a function, is it better to pass by value (which you can't change) or pass by reference - (which you can change).

Mutability has little to do with passing by-value or by-pointer. There's a reason the const keyword exists in the language. Further, what's stopping the data-structure from using a shared object to store the data meaning copies are reflected in the original object. Any reference counted or copy-on-write implementation of a data structure has the potential to allow copied objects to access the data even if &source != &destination. In short, the mutability is an implementation detail of the structure itself unless the parameter is explicitly declared const.

Side note - when you pass a param to a function it makes a copy of it within the function and destroys the copy after the end of the function.

Eh, not exactly. Things like this depend on the calling convention. Obviously it's outside the scope of someone trying to understand pointers. But still, it's just another of the many problems with your post.

Also if you want to get some dynamic memory, how are you going to hold it.

Trivial, however I DO NOT recommend this. It's pretty stupid but proves that it can work:

#include <iostream>
   
   class CSimple
   {
   public:
       CSimple() { std::cout<<"Constructor"<<std::endl; }
       ~CSimple() { std::cout<<"Destructor"<<std::endl; }
   };
   
   int main()
   {
       CSimple &c = *(new CSimple);
       delete &c;
       return 0;
   }

Notice that:

  • The program doesn't crash.
  • The destructor really is called.
Another example that demonstrates the same concept but proves the addresses are the same:

#include <iostream>
  
  class CSimple
  {
  public:
      CSimple() { std::cout<<"Constructor"<<std::endl; }
      ~CSimple() { std::cout<<"Destructor"<<std::endl; }
  };

int main()
{
      CSimple *p = new CSimple;
      CSimple &c = *p;
      std::cout<<p<<std::endl;
      std::cout<<&c<<std::endl;
      delete p;
      return 0;
}

I do not recommend either example in real-world scenarios because they are a memory leak waiting to happen. At least pointers have different member access syntax so it's a little easier to remember to free them if not using a wrapper. But a reference has the same syntax as a static object.

There are many many uses for pointers and soon you will see the use for a pointer to a pointer - that will spin you out!

Indeed.
Link to comment
Share on other sites

References are not pointers. It's important when talking about C++ to distinguish between references and pointers because both are available in the language and both are different things.

Valik you have a valid point. Pointers and references are very different and some times I use terms interchangeably which is incorrect when talking about C++. I learnt C first where references dont exist and was taught passing a pointer is passing by reference my mistake. Ill refrain from using the word reference as it will cause confusion.

To restate it when working with large data like a structure, it is better to use a pointer as it gives a performance gain. When you pass a structure or large data type to a function you are passing it by value. Passing by value means the structure or large data type has to be copied which will take longer and more memory. This is one of the main benefits of pointers copies dont have to be made. If you send the pointer, you are saving time and memory.

Mutability has little to do with passing by-value or by-pointer. There's a reason the const keyword exists in the language. Further, what's stopping the data-structure from using a shared object to store the data meaning copies are reflected in the original object. Any reference counted or copy-on-write implementation of a data structure has the potential to allow copied objects to access the data even if &source != &destination. In short, the mutability is an implementation detail of the structure itself unless the parameter is explicitly declared const.

I think your missing my point. This is a simple example of a benefit or use of pointers that has nothing to do with consts, shared object or anything else. For the purpose of learning and since I did not specify anything special conditions on the structure can we assume that it is a normal simple structure containing only simple data types?

I do argue that passing by pointer or passing by value does have an impact on mutability. If you create a double like num = 5, sent it by value to function foo, change it within function foo like num = 7, the change to num is not reflected in the parent function.

If you create a double like num = 5, sent it by value to function foo, change it within function foo like num = 7, the change to num is not reflected in the parent function.

Example:

CODE
#include <iostream>

using namespace std;

int main () {

double num = 5;

foo(num);

// num is still 5, not 7

cout << "The double is " << d;

return 0;

}

void foo(double num) {

num = 7;

}

Eh, not exactly. Things like this depend on the calling convention. Obviously it's outside the scope of someone trying to understand pointers. But still, it's just another of the many problems with your post.

I don't know what you mean when you say calling convention.

The point I was trying to get across is also demonstrated in the example.

In the function foo, num is declared as a double, its scope lies only within foo. Any changes made to num within the function foo are lost.

Trivial, however I DO NOT recommend this. It's pretty stupid but proves that it can work:

#include <iostream>
   
   class CSimple
   {
   public:
       CSimple() { std::cout<<"Constructor"<<std::endl; }
       ~CSimple() { std::cout<<"Destructor"<<std::endl; }
   };
   
   int main()
   {
       CSimple &c = *(new CSimple);
       delete &c;
       return 0;
   }

Notice that:

  • The program doesn't crash.
  • The destructor really is called.
Another example that demonstrates the same concept but proves the addresses are the same:

#include <iostream>
  
  class CSimple
  {
  public:
      CSimple() { std::cout<<"Constructor"<<std::endl; }

      ~CSimple() { std::cout<<"Destructor"<<std::endl; }
  };

int main()
{
      CSimple *p = new CSimple;
      CSimple &c = *p;
      std::cout<<p<<std::endl;
      std::cout<<&c<<std::endl;
      delete p;
      return 0;
}

I do not recommend either example in real-world scenarios because they are a memory leak waiting to happen. At least pointers have different member access syntax so it's a little easier to remember to free them if not using a wrapper. But a reference has the same syntax as a static object.

You have proven it is possible - however I remember you saying just because you can does not mean that you should.

I guess my statement should have been "Holding dynamic memory either using new or a function like malloc is another good use for pointers" to avoid any confusion.

CoolPenguin - I hope you don't find it too confusing - just trying to demonstrate some possible uses of pointers.

Post your code because code says more then your words can. SciTe Debug mode - it's magic: #AutoIt3Wrapper_run_debug_mode=Y. Use Opt("MustDeclareVars", 1)[topic="84960"]Brett F's Learning To Script with AutoIt V3[/topic][topic="21048"]Valuater's AutoIt 1-2-3, Class... is now in Session[/topic]Contribution: [topic="87994"]Get SVN Rev Number[/topic], [topic="93527"]Control Handle under mouse[/topic], [topic="91966"]A Presentation using AutoIt[/topic], [topic="112756"]Log ConsoleWrite output in Scite[/topic]

Link to comment
Share on other sites

No, a pointer to a reference is invalid. It's a reference to a pointer.

And I have had occasions to use a reference to a pointer. I can't recall any specific instance but it has its uses.

My bad - haven't had to use a reference to a pointer - i'll try to avoid it. Edited by bo8ster

Post your code because code says more then your words can. SciTe Debug mode - it's magic: #AutoIt3Wrapper_run_debug_mode=Y. Use Opt("MustDeclareVars", 1)[topic="84960"]Brett F's Learning To Script with AutoIt V3[/topic][topic="21048"]Valuater's AutoIt 1-2-3, Class... is now in Session[/topic]Contribution: [topic="87994"]Get SVN Rev Number[/topic], [topic="93527"]Control Handle under mouse[/topic], [topic="91966"]A Presentation using AutoIt[/topic], [topic="112756"]Log ConsoleWrite output in Scite[/topic]

Link to comment
Share on other sites

To restate it when working with large data like a structure, it is better to use a pointer as it gives a performance gain. When you pass a structure or large data type to a function you are passing it by value. Passing by value means the structure or large data type has to be copied which will take longer and more memory. This is one of the main benefits of pointers copies don't have to be made. If you send the pointer, you are saving time and memory.

You have not re-stated that. You have stated it for the first time. Previously you said:

If you have a very large data structure that you want pass to a function, is it better to pass by value (which you can't change) or pass by reference - (which you can change).

That certainly does not make it clear what you are trying to say. You only marginally make it clear with your second attempt.

I think your missing my point. This is a simple example of a benefit or use of pointers that has nothing to do with consts, shared object or anything else. For the purpose of learning and since I did not specify anything special conditions on the structure can we assume that it is a normal simple structure containing only simple data types?

It's understandable that I missed your point since it's clouded by discussion of mutability. You need to work on writing things clearly because you are failing miserably at writing clearly.

I don't know what you mean when you say "calling convention".

The point I was trying to get across is also demonstrated in the example.

In the function foo, num is declared as a double, its scope lies only within foo. Any changes made to num within the function foo are lost.

This is better phrasing.

You have proven it is possible - however I remember you saying just because you can does not mean that you should.

I guess my statement should have been "Holding dynamic memory either using new or a function like malloc is another good use for pointers" to avoid any confusion.

Correct. But suggesting it's the only way to do something is not an accurate statement which my example proves. There's a line between over-simplification and saying just enough to get a user started down the right road. I'm not a fan of over-simplification because it creates tunnel vision.

My suggestion to you is to think out what you write more. You have not been very clear in the points you are trying to get across. I understand what you mean but I also understand the language and don't really need things explained to me. The person you have been addressing does not. So over-simplifications and lack of clear explanation are not as helpful as you're trying to be.

Link to comment
Share on other sites

Valik - point taken. Assumptions lead to poor communication i'll attempt to be more vigilant in the future.

Post your code because code says more then your words can. SciTe Debug mode - it's magic: #AutoIt3Wrapper_run_debug_mode=Y. Use Opt("MustDeclareVars", 1)[topic="84960"]Brett F's Learning To Script with AutoIt V3[/topic][topic="21048"]Valuater's AutoIt 1-2-3, Class... is now in Session[/topic]Contribution: [topic="87994"]Get SVN Rev Number[/topic], [topic="93527"]Control Handle under mouse[/topic], [topic="91966"]A Presentation using AutoIt[/topic], [topic="112756"]Log ConsoleWrite output in Scite[/topic]

Link to comment
Share on other sites

I'm sorry if this is way offtopic... What if I found a pointer, lets say its pointing at 0025CC34 or I have found an address like 0025CC11 and its offset like 0025CC11+305 how do I make autoit read the value of the pointer? Lets say I want to place the value of pointer 0025CC34 into variable $Var. How would I do that?

Link to comment
Share on other sites

I'm sorry if this is way offtopic... What if I found a pointer, lets say its pointing at 0025CC34 or I have found an address like 0025CC11 and its offset like 0025CC11+305 how do I make autoit read the value of the pointer? Lets say I want to place the value of pointer 0025CC34 into variable $Var. How would I do that?

It is way off-topic.
Link to comment
Share on other sites

Valik, do you know if there are any differences between passing a pointer and a reference when it comes to how the data is pushed on to the stack in the stdcall calling convention? My basic instinct says that there aren't, but you'll never know. I'm finding it hard to find info about the subject ^_^

Broken link? PM me and I'll send you the file!

Link to comment
Share on other sites

Valik, do you know if there are any differences between passing a pointer and a reference when it comes to how the data is pushed on to the stack in the stdcall calling convention? My basic instinct says that there aren't, but you'll never know. I'm finding it hard to find info about the subject ^_^

References are implemented as pointers, IIRC. This may not be defined by the standard but I think all the most common implementations use this convention.
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...