By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
449,421 Members | 1,245 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 449,421 IT Pros & Developers. It's quick & easy.

Why pointers?

P: n/a
Before I had a good idea how to use pointers, I was wondering - first,
how to use them. And second, of what value would they be.

Now that I have at least a pretty good idea of how to use them, I am
still wondering of what real value are they?

I'll admit - its pretty sexy to be able to assign values indirectly,
but what I'm trying to figue out is why it is any better than assigning
the values directly.

Declare a pointer, point it at some element of an array, dereference
it. Whew - seems like a lot of work when you can just: myArray[5]
=6.

Any comments would be appreciated. As you can tell, I am new to C++ -
but I love it!

Nov 22 '05 #1
Share this Question
Share on Google+
12 Replies


P: n/a
* arganx:
Before I had a good idea how to use pointers, I was wondering - first,
how to use them. And second, of what value would they be.

Now that I have at least a pretty good idea of how to use them, I am
still wondering of what real value are they?

I'll admit - its pretty sexy to be able to assign values indirectly,
but what I'm trying to figue out is why it is any better than assigning
the values directly.

Declare a pointer, point it at some element of an array, dereference
it. Whew - seems like a lot of work when you can just: myArray[5]
=6.


<url:
http://home.no.net/dubjai/win32cpptut/special/pointers/preview/pointers_01__alpha3.doc.pdf>

where the only mention you will find of arrays is that they're not
discussed... ;-)

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Nov 22 '05 #2

P: n/a
arganx wrote:
Before I had a good idea how to use pointers, I was wondering - first,
how to use them. And second, of what value would they be.

Now that I have at least a pretty good idea of how to use them, I am
still wondering of what real value are they?

I'll admit - its pretty sexy to be able to assign values indirectly,
but what I'm trying to figue out is why it is any better than assigning
the values directly.

Declare a pointer, point it at some element of an array, dereference
it. Whew - seems like a lot of work when you can just: myArray[5]
=6.

Any comments would be appreciated. As you can tell, I am new to C++ -
but I love it!


Some random thoughts, probably incomplete and not in any particular order:

1) Pointers let you get something back out of a function. Eg.

std::vector<int> v;

void foo(std::vector<int>* x) ...

If you're going to build up a lot of "stuff" in foo() you may not want
to return it by value.
2) Yes, the more C++ / OO thing to do in #1 is to use a reference.
However, one advantage pointers have over references is the ability to
reseat them. If and when that may be a factor for you...
3) Pointers can be faster for array indexing. Consider an array A of
objects of type foo. To access an element via A[i] the compiler
actually calculates A (a foo*) + sizeof(foo) * i; That's a lot of work.
Suppose you just had an iterator ... I mean pointer ;-) ... to a foo,
you'd be there. So using pointers to index through arrays can save you
a little time, if you need it. (obviously profile first)
4) Pointers let you do cool OO stuff ;-) such as access an object of
some derived type via a pointer to a base class type. Thereby reaping
the benifits of virtual function dispatch, polymorphism, code reuse,
etc. Yes, references can be used in much the same way.
5) Pointers may be necessary if an object is too big to create staticly
or on the stack as a local variable. Here again, references may help.

6) Pointers let you explicitly and intentionally control the lifetime of
an object beyond what {} can do for you in a local scope.
7) Pointers let you introduce all kinds of interesting bugs into your
code. ;-)
Nov 22 '05 #3

P: n/a
arganx wrote:
Before I had a good idea how to use pointers, I was wondering - first,
how to use them. And second, of what value would they be.

Now that I have at least a pretty good idea of how to use them, I am
still wondering of what real value are they?
They have many uses, but usually you only use them when you have to. They
aren't used as much in C++ as in C because you have references in C++ that
also address indirectly, and std::string is often used instead of char *.
Some of the uses they still have include:
- every 'new' expression returns a pointer, and there are plenty of those in
C++ programs
- polymorphism (of the virtual function kind) requires a pointer or a
reference, but references are often unsuitable, e.g., you can have a
collection of Shape*, but not Shape&
- iterating over an array (which still have their uses)
- char * or const char * where std::string is unnecessary
- API calls in a given OS sometimes require or return an address
- where reseating is necessary, since references can't be reseated
- where a null value is needed, since references don't have one
I'll admit - its pretty sexy to be able to assign values indirectly,
but what I'm trying to figue out is why it is any better than
assigning the values directly.
You wouldn't use a pointer if you can do the assignment directly.
Declare a pointer, point it at some element of an array, dereference
it. Whew - seems like a lot of work when you can just: myArray[5]
=6.


Then just say myArray[5] = 6.

Did you mean to ask just about pointers, or indirect addressing in general?

DW
Nov 22 '05 #4

P: n/a
arganx wrote:

I'll admit - its pretty sexy to be able to assign values indirectly,
but what I'm trying to figue out is why it is any better than assigning
the values directly.

Declare a pointer, point it at some element of an array, dereference
it. Whew - seems like a lot of work when you can just: myArray[5]
=6.


Right.
But note: This is not a typical usage of pointers. Neither in C++ nor
in C.

A typical usage of pointers comes into play when dynamic memory
management comes into play: When you need to create a dynamic
data structure without knowing beforehand how large that structure
is going to be.

C++ has some pre build containers with it which easen the whole process,
but if you need something special, then there often is no way around
building your own container. For that you will need dynamic memory
allocation and for that you will need pointers.

--
Karl Heinz Buchegger
kb******@gascad.at
Nov 22 '05 #5

P: n/a

arganx wrote:
Before I had a good idea how to use pointers, I was wondering - first,
how to use them. And second, of what value would they be.

Now that I have at least a pretty good idea of how to use them, I am
still wondering of what real value are they?

I'll admit - its pretty sexy to be able to assign values indirectly,
but what I'm trying to figue out is why it is any better than assigning
the values directly.

Declare a pointer, point it at some element of an array, dereference
it. Whew - seems like a lot of work when you can just: myArray[5]
=6.

Any comments would be appreciated. As you can tell, I am new to C++ -
but I love it!


Dynamic memory tracking has already been mentioned.

There are some dynamic data structures such as lists and trees that
make heavy use of pointers. For example, a simple list node would look
something like this:

struct lnode
{
int dataValue; // data for this list node
struct lnode *next; // location of next node in list
};

The next member explicitly points to the next element in the list.
List-type structures are useful if you're doing a lot of insertions and
deletions; all you need to do is shuffle pointers.

Nov 22 '05 #6

P: n/a
"arganx" <ar*******@yahoo.com> writes:
Before I had a good idea how to use pointers, I was wondering - first,
how to use them. And second, of what value would they be.

Now that I have at least a pretty good idea of how to use them, I am
still wondering of what real value are they?
Transfer of ownership, and lifetime other than program or function.

Pointers are essential in implementation of std::string, std::vector,
std::list and lots of other stuff in the standard library.
I'll admit - its pretty sexy to be able to assign values indirectly,
(You can do this with references too).
but what I'm trying to figue out is why it is any better than assigning
the values directly.

Declare a pointer, point it at some element of an array, dereference
it. Whew - seems like a lot of work when you can just: myArray[5]
=6.
And if you don't see any gain in using pointers instead, just stick to
the direct access. No need to complicate things more than necessary.

std::vector<int> myArray(10);
myArray[5] = 6;
Any comments would be appreciated. As you can tell, I am new to C++ -
but I love it!


An excercise for you: Implement a binary tree (of integers) with
the following interface:

class Tree
{
public:
Tree();
Tree(const Tree& x);
~Tree();

Tree& operator = (const Tree& x);

void insert(int x);
void print(std::ostream& x); // print values sorted

private:
/*
* implementation details here
* three data members: value, left, and right,
* Where left contains everything smaller than value,
* and right everything larger than or equal to value
*/
};

#include <iostream>

int main(void)
{
Tree t;
t.insert(42);
t.insert(11);
t.insert(17);
t.insert(99);
t.insert(1);

/* Here is what the tree should look like now:
*
* 42
* / \
* 11 99
* / \
* 1 17
*
*/
t.print(std::cout); // output " 1 11 17 42 99"
return 0;
}

When you have solved this you will know one situation
where pointers are useful.

/Niklas Norrthon
Nov 23 '05 #7

P: n/a
Thank you all for your comments. I now have a lot to study and think
about. Seems like just when I think I've learned something, a door
opens to show me that I've just started.

A serious question: Is it possible to truthfully say "I have complete
knowledge of the C++ language." And if so, how long would that likely
take? I don't mean possible applications as this would be infinite,
but just the technical knowledge.

Nov 23 '05 #8

P: n/a
On 2005-11-22, arganx <ar*******@yahoo.com> wrote:
Thank you all for your comments. I now have a lot to study and
think about. Seems like just when I think I've learned
something, a door opens to show me that I've just started.

A serious question: Is it possible to truthfully say "I have
complete knowledge of the C++ language."


No. Well, not likely. Check out Herb Sutter's _Guru of the Week_
columns on the internet when you wish to be humbled.

It is a big language, and most features are combinable. Even if
you were able to learn every individual feature, there's still a
combinatorial explosion that no one person will ever master. That
doesn't count the 3rd party libraries you'd need to know for your
chosen application domain.

--
Neil Cerutti
Nov 23 '05 #9

P: n/a
arganx wrote:
Before I had a good idea how to use pointers, I was wondering - first,
how to use them. And second, of what value would they be.

Now that I have at least a pretty good idea of how to use them, I am
still wondering of what real value are they?
Pointers are unnecessary to express computation. Everything can be
expressed in a functional programming language which banishes
assignment.

If you never assign to a variable or any part of an object, you don't
care whether you are dealing with reference or value passing semantics.

If a function does something with an object, it simply takes that
object as an argument. You don't care whether it's a reference or a
copy is made or what.

Pointers come into play when you allow assignment. Suddenly, the
identity of an object matters, because when you change an object, every
place in the program that has a pointer to that same object will see a
changed object. Whereas copies of the object are immune to that change.

You can now tell the difference between a function which did something
to a copy of an object, and one which received a reference to the
caller's object.
I'll admit - its pretty sexy to be able to assign values indirectly,
but what I'm trying to figue out is why it is any better than assigning
the values directly.


Because when you assign values directly, you fail to separate the
algorithm from the data that it operates on. The code knows where to
find an instance of the data to work on. If you want it to do something
with a different instance of the data, you have to instantiate a new
version of that code, in which the direct reference is patched to refer
to the new instance.

A pointer just lets you pass in the identity/location of the data to be
worked on, so the same instance of the code can do the job.

Don't laugh, this has been done! At one point, the Linux kernel had a
driver for ATAPI CDROM devices which was compiled multiple times if you
wanted multiple devices. If you wanted to support two of these drives,
the driver got compiled twice. The same C translation unit, but with
some preprocessor symbols being altered to avoid conflicts among the
instances.

This allowed the driver to have only direct references to static
variables, rather than pass around some numeric index or pointer
representing which instance of the CD-ROM drive it was working with.

I will tell you another funny story. Years ago as a little boy, I was
learning to hack in 6502 machine language. I was so eager to get coding
(as I still am today) that I put down the book and decided to write a
fast routine to flip the pixels on the high resolution screen from
black to white and vice versa.

I considered the simple instructions I knew so far and then hit a
stumbling block. How to make the program iterate over the video buffer?
I knew how to load from a fixed address to a register, compare, and
branch and that sort of thing.

So I wrote a self-modifying program. The program contained an
instruction to fetch data from a fixed address, invert the bits, and
then store back to that address. The looping step would then patch
those instructions to the next address, compare and loop back. Worked
like a charm, but I didn't like how the program ended up being a
different program at the end of the loop, and how it had to know its
own location in memory.

I then went back to the book. The next chapters covered the use of
pointers. Or rather, various addressing modes, allowing a combination
of data in memory and registers to achieve indirect references. I was
relieved: I knew there had to be a better way! Soon, I rewrote that
routine with one that wasn't self-modifying.

But you know, the original code didn't really avoid the use of
pointers. It just abused storage locations within the program's
instructions itself into behaving like pointers.

To actually avoid pointers for real (or almost!), you'd have to write a
huge, long program, in which each word of the screen buffer is
manipulated by a separate instruction. No looping!

I say almost, because even that would not have eliminated the use of a
pointer: the instruction pointer by means of which the CPU steps
through the program's instructions!!!

You can't do anything on a Von Neumann box without pointers, because
you can't even step from one instruction to the next. To make a machine
without pointers, you need a different architecture. Like maybe
something that feeds a tape over a read/write head. But then the
position of the tape is a pointer. :)

Nov 23 '05 #10

P: n/a
arganx wrote:
Before I had a good idea how to use pointers, I was wondering - first,
how to use them. And second, of what value would they be.

Now that I have at least a pretty good idea of how to use them, I am
still wondering of what real value are they?
Pointers are unnecessary to express computation. Everything can be
expressed in a functional programming language which banishes
assignment.

If you never assign to a variable or any part of an object, you don't
care whether you are dealing with reference or value passing semantics.

If a function does something with an object, it simply takes that
object as an argument. You don't care whether it's a reference or a
copy is made or what.

Pointers come into play when you allow assignment. Suddenly, the
identity of an object matters, because when you change an object, every
place in the program that has a pointer to that same object will see a
changed object. Whereas copies of the object are immune to that change.

You can now tell the difference between a function which did something
to a copy of an object, and one which received a reference to the
caller's object.
I'll admit - its pretty sexy to be able to assign values indirectly,
but what I'm trying to figue out is why it is any better than assigning
the values directly.


Because when you assign values directly, you fail to separate the
algorithm from the data that it operates on. The code knows where to
find an instance of the data to work on. If you want it to do something
with a different instance of the data, you have to instantiate a new
version of that code, in which the direct reference is patched to refer
to the new instance.

A pointer just lets you pass in the identity/location of the data to be
worked on, so the same instance of the code can do the job.

If you think that's ridiculous, I can cite a recent example where this
has been done in production code (not counting the millions of bloated
C++ templates out there which instantiate nearly identical versions of
the same code). Not long ago, the Linux kernel had a driver for ATAPI
CDROM devices which was compiled multiple times if you had more than
one of these drives attached to your machine and wanted to drive each
one. The driver was compiled as many times as the number of instances
you wanted. Nearly the same C translation unit was passed through the
compiler multiple times, only with some preprocessor symbols being
altered to avoid conflicts among the instances.

This allowed the driver to have only direct references to static
variables, rather than pass around some numeric index or pointer
representing which instance of the CD-ROM drive it was working with.

I will tell you another funny story. Years ago as a little boy, I was
learning to hack in 6502 machine language. I was so eager to get coding
(as I still am today) that I put down the book and decided to write a
fast routine to flip the pixels on the high resolution screen from
black to white and vice versa.

I considered the simple instructions I knew so far and then hit a
stumbling block. How to make the program iterate over the video buffer?
I knew how to load from a fixed address to a register, compare, and
branch and that sort of thing.

So I wrote a self-modifying program. The program contained an
instruction to fetch data from a fixed address, invert the bits, and
then store back to that address. The looping step would then patch
those instructions to the next address, compare and loop back. Worked
like a charm, but I didn't like how the program ended up being a
different program at the end of the loop, and how it had to know its
own location in memory.

I then went back to the book. The next chapters covered the use of
pointers. Or rather, various addressing modes, allowing a combination
of data in memory and registers to achieve indirect references. I was
relieved: I knew there had to be a better way! Soon, I rewrote that
routine with one that wasn't self-modifying.

But you know, the original code didn't really avoid the use of
pointers. It just abused storage locations within the program's
instructions itself into behaving like pointers.

To actually avoid pointers for real (or almost!), you'd have to write a
huge, long program, in which each word of the screen buffer is
manipulated by a dedicated sequence of instructions, which is hard
coded with a direct reference to that word's address. If the buffer has
some 8000 words you string together a 24,000 instruction program. load,
invert, store, load, invert, store.

LDA $2000 ; load first 8 bit word of frame buffer into accumulator
EOR #$FF ; flip the accumulator's bits
STA $2000 ; store back.

LDA $2001 ; do the next 8 bit word
EOR #$FF
STA $2001

On that machine, there wouldn't have been enough space to store that
program. :)

I say this almost eliminates pointers, because there is one pointer
left: the instruction pointer by means of which the CPU advances
forward through these instructions!!!

You can't do anything on a Von Neumann box without pointers, because
you can't even step from one instruction to the next. To make a machine
without pointers, you need a different architecture. Like maybe
something that feeds a tape over a read/write head. But then the
position of the tape is a pointer. :)

Nov 23 '05 #11

P: n/a
arganx wrote:

Thank you all for your comments. I now have a lot to study and think
about. Seems like just when I think I've learned something, a door
opens to show me that I've just started.

A serious question: Is it possible to truthfully say "I have complete
knowledge of the C++ language." And if so, how long would that likely
take? I don't mean possible applications as this would be infinite,
but just the technical knowledge.


You know 'chess'? I mean, the game 'chess'.

Well. The pieces are simple. The rules of the game are simple.
Each piece moves in simple ways.
And yet the combination of pieces, strategies and moves makes it
an incredible complicated game. I think no one on earth would
ever say: I have completely mastered chess.

Same with programming languages.
The problem is not of understanding each and every part of C++
(although this is an outstanding job on its own). The problem
comes when combining all those individual pieces to form a whole
program.

--
Karl Heinz Buchegger
kb******@gascad.at
Nov 24 '05 #12

P: n/a

"Phil Staite" wrote
7) Pointers let you introduce all kinds of interesting bugs into your
code. ;-)


Yes indeed. I had to debug someone's program for an embedded
system. Only after moving variables out to external RAM instead
of using internal RAM I found the function using a pointer to the data
array. The problem was found. No bounds checking. Pointers can be
fun indeed unless you know how to use them. I just rewrote the function
to make it work. What made it even more fun was the equipment was in
a 911 call center (PSAP). Life can be fun at times.

Just remember: Dial 911 because sh*t happens.

Tom the Canuck.
Dec 3 '05 #13

This discussion thread is closed

Replies have been disabled for this discussion.