The ProgrammersTalk Community
Forum Register Search Today's Posts Mark Forums Read
Register

Go Back   The ProgrammersTalk Community > General Programming > C / C++


Welcome to the The ProgrammersTalk Community forums.

You are currently viewing our boards as a guest which gives you limited access to view most discussions and access our other features. By joining our free community you will have access to post topics, communicate privately with other members (PM), respond to polls, upload content and access many other special features. Registration is fast, simple and absolutely free so please, join our community today!

If you have any problems with the registration process or your account login, please contact contact us.
Tags:

Reply
 
LinkBack Thread Tools    Display Modes   
  #1 (permalink)  
Old 08-02-2007, 01:57 PM
HelloWorld's Avatar
HelloWorld HelloWorld is offline
Programming Expert
Awards Showcase
Quality Tutorial 
Total Awards: 1
Join Date: Jun 2007
Location: In front of computer...
Posts: 1,110
iTrader: (0)
HelloWorld will become famous soon enoughHelloWorld will become famous soon enoughHelloWorld will become famous soon enough
Icon9 What's pointer in C++?

What is this really?
When I read it online, it says that it just refers to the memory location. But, when should we use this? How is it useful for our program? It looks pretty cool where we can access the exact location of a variable in a memory, but why should we care? shouldn't it retrieve it automatically for us each time we call the variable?

__________________
PHP Code:
System.out.println("Hello World!"); 

Digg this Post! Del.Icio.Us this Post! Technorati this Post! Furl this Post! Mister Wong this Post! Newsvine this Post! Spurl this Post! Reddit this Post! Netscape this Post!
Reply With Quote
  #2 (permalink)  
Old 08-02-2007, 02:04 PM
HelloWorld's Avatar
HelloWorld HelloWorld is offline
Programming Expert
Awards Showcase
Quality Tutorial 
Total Awards: 1
Join Date: Jun 2007
Location: In front of computer...
Posts: 1,110
iTrader: (0)
HelloWorld will become famous soon enoughHelloWorld will become famous soon enoughHelloWorld will become famous soon enough
PHP Code:
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
int main() {
int *pointer
int test 5;
pointer = &test;
cout << "Enter value for the int test: ";
cin >> test;
cout << *pointer << endl;
return 
0;

LOL, just tried it out.. seems the same thing as when we use local variable as usual.. how can we increase efficiency by using pointers..?

__________________
PHP Code:
System.out.println("Hello World!"); 

Digg this Post! Del.Icio.Us this Post! Technorati this Post! Furl this Post! Mister Wong this Post! Newsvine this Post! Spurl this Post! Reddit this Post! Netscape this Post!
Reply With Quote
  #3 (permalink)  
Old 08-02-2007, 05:14 PM
Bench Bench is offline
Full Programmer
Join Date: Jul 2007
Location: UK
Posts: 111
iTrader: (0)
Bench is on a distinguished roadBench is on a distinguished roadBench is on a distinguished roadBench is on a distinguished roadBench is on a distinguished road
Welcome to one of the topics in C and C++ which (unnecessarily) causes a lot of confusion to people who first stumble across them.

Firstly, a pointer is a variable which holds an address in memory - Indeed, nothing special about that.. The truth is you should never care where an object is stored... but the data it holds isnt intended to be seen by the user, its intended to be used as a "placeholder" so that objects in memory can be passed around without being copied.

If you like, you can think of pointers in much the same way that Java uses references (Notice how, in java, you never "see" the data contents of a reference, you just know that its there, and at the other end is an object.. Hopefully!)

The main difference is that java is rather good at cleaning up the mess made by its references. On the other hand, C and C++ isn't good at cleaning up mess made by 'pointers', and allows you to do all sorts of horrible things if you're not careful. (I like to think of Java references as "smart pointers", which stop the programmer from doing "bad" things like leaking memory or accessing memory which doesn't belong to the program. Of course, syntax is a little different too, but that's a minor point)

C++ uses pointers for a bunch of things:
- Creating objects at runtime
- Polymorphism (Note that this is done in Java through base-class references. in C++ its done through base-class Pointers)
- As iterators for "raw" arrays (Java uses References as iterators for its collection classes. C/C++ does the same trick with pointers in arrays )
- Also, pointers are used with alot of C-style code, where you'll find yourself dealing directly with low-level constructs (C has no "string" data type, and it uses pointers to deal with arrays of characters.. yuck!)



The kind of example you posted, I believe, is often used as a contrived way of showing how pointers are used for passing references around. The example is completely detached from any real-world use of C++ pointers (as far as I can see anyway, C++ has a better way which avoids pointers). Pointers in C++ don't really become "useful" until you get past the basic language stuff, and onto OO design, data structures, etc.


Personally, I think pointers are the single most badly-explained topic across books, tutorials and reference websites. So, I won't add to that by attempting to give my own example. I think the best way to understand pointers is to leave them alone until you come across a problem where they're actually useful.

__________________

Digg this Post! Del.Icio.Us this Post! Technorati this Post! Furl this Post! Mister Wong this Post! Newsvine this Post! Spurl this Post! Reddit this Post! Netscape this Post!

Last edited by Bench : 08-02-2007 at 05:48 PM.
Reply With Quote
The Following User Says Thank You to Bench For This Useful Post:
HelloWorld (08-02-2007)
  #4 (permalink)  
Old 08-02-2007, 06:51 PM
HelloWorld's Avatar
HelloWorld HelloWorld is offline
Programming Expert
Awards Showcase
Quality Tutorial 
Total Awards: 1
Join Date: Jun 2007
Location: In front of computer...
Posts: 1,110
iTrader: (0)
HelloWorld will become famous soon enoughHelloWorld will become famous soon enoughHelloWorld will become famous soon enough
Thanx a lot Bench
Let me know if I'm wrong, so pointer is basically change the primitive type variable to be a reference type? Is that what's pointer does? (Since that's what a reference type variable a.k.a Object does too... )

__________________
PHP Code:
System.out.println("Hello World!"); 

Digg this Post! Del.Icio.Us this Post! Technorati this Post! Furl this Post! Mister Wong this Post! Newsvine this Post! Spurl this Post! Reddit this Post! Netscape this Post!
Reply With Quote
  #5 (permalink)  
Old 08-02-2007, 07:38 PM
rpgfan3233 rpgfan3233 is offline
PT Staff
Awards Showcase
Quality Tutorial Quality Tutorial Quality Tutorial Quality Tutorial 
Total Awards: 4
Join Date: Jul 2007
Posts: 118
iTrader: (0)
rpgfan3233 has a spectacular aura aboutrpgfan3233 has a spectacular aura aboutrpgfan3233 has a spectacular aura aboutrpgfan3233 has a spectacular aura aboutrpgfan3233 has a spectacular aura about
Quote:
Originally Posted by HelloWorld View Post
Thanx a lot Bench
Let me know if I'm wrong, so pointer is basically change the primitive type variable to be a reference type? Is that what's pointer does? (Since that's what a reference type variable a.k.a Object does too... )
Not quite. Really a pointer is just a pointer to a memory address. You could do the following in C++ and get a hexadecimal address:
Code:
using std::cout;
using std::endl;

int x = 4;
int* x_ptr = &x;
cout << x_ptr << ":\t" << *x_ptr << endl; //hexadecimal address followed by value held at that address
(*x_ptr)++; //increment the value at x_ptr
cout << &x << ":\t" << x << endl; //same idea, but after the increment of the value at the address held by the pointer and using the actual variable, not the pointer to the variable
A pointer is really just a special term for a variable that holds a memory address. If you modify the value at that memory address, it means that the value of the pointee (the address being pointed to) is also changed. By the way, C++ has references too, though I'm not sure they are anything like Java's references:
Code:
using std::cout;
using std::endl;

int x = 4;
int& x_ref = x;
cout << &x_ref << ":\t" << x_ref << endl; //hexadecimal address followed by value held at that address
x_ref++; //increment the value at x_ref
cout << &x << ":\t" << x << endl; //same idea, but after the increment of the value of the reference and using the actual variable, not the reference to the variable
Strange, huh? It seems like the reference is a copy of the original variable, right? Think about this though: why are the addresses the same? A reference is similar to a pointer, but there is one really big difference between them: a reference only references a single variable for the duration of the scope of the reference. A pointer can be reassigned many times to various memory addresses if necessary. It is essentially the object itself. A good explanation of what a reference is can be found at [8] References, C++ FAQ Lite

The simplest explanation of reference vs pointer:
pointers hold a memory address, whether it is the address of a variable or a NULL pointer, where there is no memory address held
references are aliases to the object it represents

Arrays are really just pointers since an array is merely a start address (wherever the start of the data is) and an memory offset (value) for each element that the array holds. *(x + n) is the equivalent of x[n]. If you really wanted to, you could get the offset address (not to be confused the actual memory offset value) using (x + n) instead of &x[n]. To get the memory offset (value), you would use (x + n) - x or &x[n] - x. As you can see, things can get a bit complicated when working with pointers, which is why a programmer must be careful when using them. References are only as safe as how you use them, so while slightly "safer" than pointers, don't think of them as a cushion to fall back on because that can lead to error-prone code.

__________________
"C makes it easy to shoot yourself in the foot; C++ makes it harder, but when you do it blows your whole leg off."
-- Bjarne Stroustrup, creator of what is now known as C++
For more quotes by Bjarne Stroustrup, check out http://www.research.att.com/~bs/bs_faq.html#really-say-that.
Digg this Post! Del.Icio.Us this Post! Technorati this Post! Furl this Post! Mister Wong this Post! Newsvine this Post! Spurl this Post! Reddit this Post! Netscape this Post!
Reply With Quote
The Following User Says Thank You to rpgfan3233 For This Useful Post:
HelloWorld (08-03-2007)
  #6 (permalink)  
Old 08-03-2007, 05:15 AM
Bench Bench is offline
Full Programmer
Join Date: Jul 2007
Location: UK
Posts: 111
iTrader: (0)
Bench is on a distinguished roadBench is on a distinguished roadBench is on a distinguished roadBench is on a distinguished roadBench is on a distinguished road
Quote:
Originally Posted by HelloWorld View Post
Thanx a lot Bench
Let me know if I'm wrong, so pointer is basically change the primitive type variable to be a reference type? Is that what's pointer does? (Since that's what a reference type variable a.k.a Object does too... )
I have a feeling your understanding of an "object" is a little different, perhaps I should clarify from a C++ perspective:

An object is something stored in memory, with a certain type, eg, int, double, some class-type, etc (What distinguishes the object from raw 1's and 0's is the fact that the type tells the program what kind of data its dealing with, and how big the area of memory is, otherwise the data would be meaningless)

Following on from that, A variable is a named object. Neither objects nor variables have anything to do with references in C++.

Perhaps, java text books restrict the term 'object' to mean "an instance of a class" - Most probably because Java doesn't allow variables of a class. in C++ an 'object' is a general term, which can be an instance of a class, or of a built-in type (int, float, etc).
I think Java texts muddy the water a little by interchanging the terms "object" and "reference" - Something which it really ought not to. Here's why: (Apologies for using java in a C++ forum)
Code:
public class Mess {
    int i;
    
    public static void main(String args[])
    {
        Mess my_mess = new Mess(5);
    }

    public Mess(int ii)
    {
        i = ii;
    }
}
In the above java snippet, my_mess is a reference (a java smart pointer) to an object.
However, the object itself, the new Mess instance has no name, and isn't 'owned' by the my_mess reference (in fact, its owned by the Java garbage collector) - the two things are seperate entities, but the reference can be used to access that object. However, the object is not dependent on the existance of the reference, nor is the reference dependent on the existance of the object.

in C++, you can do the same thing with pointers
Code:
class Mess
{
    int i;
public:
    Mess(int ii)
    {
        i = ii;
    }
};

int main()
{
    Mess* my_mess = new Mess(5);
}
This creates a pointer called my_mess, and an un-owned object (C++ hasn't got a garbage collector) of type Mess.


Contrast this with something that Java won't let you do, which is, create a variable of a class
Code:
class Mess
{
    int i;
public:
    Mess(int ii)
    {
        i = ii;
    }
};

int main()
{
    Mess my_mess = Mess(5);
}
In this case, my_mess is the named object (Variable), type Mess. The variable owns the object in memory, and is responsible for its creation/destruction.

Since the variable owns object in memory, both are totally dependent on one another - the variable cannot be used if the object is destroyed (This is usually ok, because the object lasts as long as the variable exists), and the object cannot be used when the variable is destroyed (Sometimes a problem which can happen if you let a pointer keep ahold of the address of the object after the variable dies)



Note: I should probably correct myself from my earlier post - I think I implied that a pointer needed to be a named object (a variable), although, actually a pointer can be an unnamed object too


Edit:
Quote:
Originally Posted by rpgfan3233 View Post
By the way, C++ has references too, though I'm not sure they are anything like Java's references:
Not very much alike, aside from the basic semantics, they're quite different - Java references are like Boost/C++ smart pointers - they're modifiable, copyable, and reference-counted for a built-in garbage collector.

__________________

Digg this Post! Del.Icio.Us this Post! Technorati this Post! Furl this Post! Mister Wong this Post! Newsvine this Post! Spurl this Post! Reddit this Post! Netscape this Post!

Last edited by Lee : 08-03-2007 at 06:58 AM. Reason: Keeping things tidy.
Reply With Quote
The Following User Says Thank You to Bench For This Useful Post:
HelloWorld (08-03-2007)
Reply


Thread Tools
Display Modes

   Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On



All times are GMT -7. The time now is 10:41 PM. Powered by vBulletin
Copyright © 2000 - 2007, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO © 2007 ProgrammersTalk Sedo - Buy and Sell Domain Names and Websites project info: programmerstalk.net Statistics for project programmerstalk.net etracker® web controlling instead of log file analysis


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50