I have been reading about pointers, which IS confusing. I'm sure there is a purpose, but I don't know why I need them yet. For example

var1 = 23;        // assigning 23 to var1
var2 = var1;      // assigning the value of var1 to var2
var3 = &var1;     // assigning the address of var1 to var3

I think I might know what pointers do. I don't, however, know what the practical use of a pointer is. From what I've learned about pointes, is that they directly give the value of whats at that location in memory.

My question is: what is the practical use of pointers?

Examples && Explanations = *Welcomed :cheesy:

i havent slept in days and i hope i dont say something completely stupid here:

pointers contain the memory location of a variable. one of the reasons that this is useful concerns memory efficiency. if you're passing a variable to a function then the function has to make another copy of that variable and if that variable is an object of type NUCLEAR_REACTOR_PLAN, then you might run out of memory mighty fast. but if you pass a variable which points to the NUCblahblahblah variable's address, then you dont have to make the copy, you can just work with the original. Another potential use of pointers is in the implementation of a template class.

I got the similar problem with you, Geek-Master. What kaiser<lucy> said is still a little bit abstract for me.

So Geek-Master have you tried the dynamic memory allocation using new and delete operator? They could only deal with pointers.

Now my own problem comes. Books say we can use new operator to reserve memory for array of unknown size like this:
<code>
int* ptr = new int[100]; //the array ptr has interger type and 100 elements
</code>

Now another version:
<code>
int n;
int ptr[n];

cin >> n; //ask user to enter size of array, now array has size
</code>

So what is the difference between the two versions of array declaration?
In both cases the array is declared but doesn't have defined-size unless it is determined during runtime.

Sorry the version using new operator should look like this:

<code>

int n;
int* ptr = new int[n]; //the array ptr has interger type but size not defined

cin >> n; //ask user to enter size of array, now array has size

</code>


Sorry for making confusions

First, use [ code ] [/ code ] tags (not <code>)

>>int ptr[n];
Don't declare an array with undefined dimention.

Let me quote the lecture notes from my school:

int main(void)
{
     cout <<  “How many students? “;
     cin   >> n;

     //Declare an array to hold students' information
     int *grades = new int[n];

    . . . . . .
    . . . . . .
    . . . . . .
 }

The above example they call it 'dynamic array'. The value of n is essentially unknown during compilation time. Am I right? Now look at this:

int main(void)
{
     cout <<  “How many students? “;
     cin   >> n;

     //Declare an array to hold students' information
     int grade[n];

    . . . . . .
    . . . . . .
    . . . . . .
 }

The size of n is also not known until the programme is run. Then what is the point to use pointer and new operator to declare the array in the first case?

>Then what is the point to use pointer and new operator to declare the array in the first case?
Because the second case is ill-formed and thus, illegal in C++. Array sizes in C++ must be constant integral values. If it works when you try it then that's because your compiler allows it as an extension. Only the first case is guaranteed to be correct (assuming n is already defined).

Pointers are still a vast subject that I am still working on to learn. I still need time to look over all of the technical writing of it all. I just needed to grasp the purpose of them.

but if you pass a variable which points to the NUCblahblahblah variable's address, then you dont have to make the copy, you can just work with the original. Another potential use of pointers is in the implementation of a template class.

by: kaiser<lucy>

I can kinda see the purpose now, dealing with memory usage. Thanks :cheesy:

pointers are c++ most useful things and is what sets it aside from other languages. Just to name a few uses:

Dynamic arrays
Linked lists
Memory management (eg. passing pointers rather than objects, alloc'ing memory ect..)
Binary Trees and Heaps (great for gaming)
Speed improvement (you can simplify code in some cases with pointers/function ptrs)

the last few being especially important in game programming.

If you still arent sure they are useful then try this: make a list class (or a set of functions) that can grow and shrink in size BUT not lose the contents (so it is NOT dynamic arrays...) without using STL (which, I believe, is a steam based linked list anyway). TIP: You need a pointer to the next and previous list item for it to work!

Comments
I finally figured out 1o0oBhP's example and it makes since

In C/C++, another valuable use of pointers is to point to an array of charactors. C doesn't have a string type, and instead you can use an array of char like this:

char name[20];

but to do any operations on that name, you need to refer to the array of char, not a string as a whole. like this:

void MakeUppercase( char name[20] )

and that assumes you know at compile time how big the array is. You probably don't, and so would probably say something more like:

void MakeUppercase( char name[] )

or

void MakeUppercase( char* name )

both of which pass pointers to the array of chars.

It is because of this that there are 'standard library' classes like std::string which try to do all the dirty work for you. There are also the older C-runtime library routines like strcpy() and strcat() and the like that do many common operations on arrays of chars. All of these are (or can be) written in C using pointers to chars.

pointers are c++ most useful things and is what sets it aside from other languages. Just to name a few uses:

Dynamic arrays
Linked lists
Memory management (eg. passing pointers rather than objects, alloc'ing memory ect..)
Binary Trees and Heaps (great for gaming)
Speed improvement (you can simplify code in some cases with pointers/function ptrs)

the last few being especially important in game programming.

If you still arent sure they are useful then try this: make a list class (or a set of functions) that can grow and shrink in size BUT not lose the contents (so it is NOT dynamic arrays...) without using STL (which, I believe, is a steam based linked list anyway). TIP: You need a pointer to the next and previous list item for it to work!

I think it is pretty said that I am finally getting around to what 1o0oBhP was pointing me to back in 2005. I have been looking into data structures using linked lists, binary trees and B-trees recently AND POINTERS DO HAVE A PURPOSE!

So to answer your question 1o0oBhP you would use a linked list. Each node would have its own content and two pointers. The first pointer would point to the previous node in the list and the second pointer would point to the next node in the list excluding the trailer node and header node which only point to one node for a queue type list. If you need to delete one of the nodes, all you would need to do is reassign the pointers linking to the node to be deleted and no content is lost, then destruct the node. The same will apply for adding a node.

I do agree that pointers are valuable in games. One example I found would be to use a B-tree when targetting multiple enemies to cast an area spell.

Sorry for reviving a dead topic, but...

I still don't have nearly enough programming knowledge to know what everyone was talking about here, but I think I almost sort of get pointers.

I couldn't help but think of a database and UID's. IF you had a database of customers and their orders, it would be crazy to store all of the information on the customer who placed the order in the actual field. Instead, we use a UID, a value that "points" to a record in the customers table where we can get whatever we want.

The UID of a variable would be it's location, so, in a sense, pointers are like UID's in a database. Am i getting thsi right?

Essentially, yes. Except a pointer goes one step further than a magic number: it is the index of an actual memory location.

>Except a pointer goes one step further than a magic number
Actually, it doesn't. A pointer really is just a magic number that specifies how to get to data. A pointer in the abstract sense could be an index into an array, it could be a memory address (relative or absolute), it could be a hyperlink, even an identifier is a "pointer" into a compiler's symbol table.

>it is the index of an actual memory location.
Not necessarily. The standard says that "a pointer type describes an object whose value provides a reference to an entity of the referenced type". Nowhere does it require that a pointer be the index of a memory location (ie. a memory address). The wording of the standard strongly implies this though, from the description of the address-of operator (&). However, "address" simply means a description of the object suitable for storage in an object of pointer type.

As an example, think of the ways a function pointer can be implemented. It's easier to see the function pointer referring not to the first instruction of the function itself, but being an index into a call table, an object containing information for working with the function, an activation sequence, or something more exotic. A function pointer is completely incompatible with an object pointer for this very reason, but it's still a pointer no matter how you implement it.

Now, I told you that so I could tell you this: it doesn't freaking matter. You don't need to know or care about the details of pointers to understand them or use them. The concept is trivial:

A pointer refers to a thing and gives you indirect access to that thing.

Addresses and such don't need to enter the equation. If you apply that to C++ you get this (barring variations):

Declare an object pointer by saying <type> *<identifier>; Declare a function pointer by saying <type> (*<identifier>) ( <parameter list> ); Refer nothing to a pointer by saying <pointer> = 0; Refer a thing to a pointer by saying <pointer> = &<thing>; Access an object through a pointer by saying *<pointer> Access a function through a pointer by saying (*<pointer>) ( <arguments> ) Adding to or subtracting from a pointer refers to different things in an array.

It's unfortunate that the "a pointer is a memory address" explanation is so common (hell, I use it in my pointer tutorial). The trap is that using memory addressing to describe pointers is so convenient. One assumes that a programmer understands memory, so using that as a foundation to describe pointers theoretically makes the learning process easier because there's an immediate example for practical use.

since i do not have any knowledge yet about these pointers,i want to ask questions

i don't have my source code with me now because i did that at school
i did something like this:

char* color;

//then i have these case statements 
//what i wanted was when a case has been chosen,the variable type will be assigned with something like this

case '1':
color = "blue";
break;
case '2':
color = "red";
break;

//then will display:
std::cout<<"color is "<<color;

my code was like that

now my questions:

1) is that what you call a pointer?

2) did i use that one the proper/right way?

i was just doing a trial and error to get the output i wanted,and to my surprise this one did the trick XD

>1) is that what you call a pointer?
Yes, color is a pointer to char and you're pointing it to a string literal.

>2) did i use that one the proper/right way?
Yes, with one minor change. It should be const char *color , not char *color . The use of char* for string literals is a C-ism that's deprecated in C++ (meaning you can still do it, but your code may break in a future revision of the C++ standard).

Hey Narue,

Where does the pointer exist once it has been created, in RAM or the CPU?

>Where does the pointer exist once it has been created, in RAM or the CPU?
A pointer variable isn't special, it's just another variable. The same storage rules for other variables apply.

I'm a first year CSC student and I've been trying to figure this out for a while now also, today I came across an example of how it would actually help (I'll apologize now if I don't format this code correctly, first time posting).

One of our assignment involves sorting arrays of character strings, these are the key parts of my first draft.

int main()
{
char pals[80][80];
char subString[80];

//Now assume that pals already has 35 sorted rows all filled with 80 characters a piece, I want to find the index of the row where I should stick subString in, so I start at the back and compare the subString to the rows of pals. As I go back I copy the character string in pals[n] to pals[n+1] to free a space for the array that's being inserted.

while (pals > subString) // Need to use a string function, but this is the idea
{
strcpy(pals[i+1], pals);
i--;
}

So in that instance every time you move a character array up 1 index spot, you have to copy 80 individual characters. With enough input, this can be pretty time consuming.

Now the better way...

char * pals = new char[80][80];

Then...

while (pals > subString)
{
pals[i+1] = pals;
i--;
}

Now this way if you call pals, you will get the same array that you would if you weren't using pointers, but the useful part is when you are moving pals[x] up to the next index, instead of having to copy 80 characters, you just copy the address of the first character in the string. This gives you the same end result but is a lot more efficient.

I'm sorry if it came across as confusing, but seeing as how I just found a use for them myself, I'm pretty sure I can't be way over you guys's heads like some of the really smart ones around here :) The syntax of the examples above is terrible, but I was just trying to give a really straightforward example of how those crazy pointers can help.

thanks for your service but my question is not answered properly

Comments
You didn't ask one, you just dug up a corpse and complained about the stench

I'm a first year CSC student and I've been trying to figure this out for a while now also, today I came across an example of how it would actually help (I'll apologize now if I don't format this code correctly, first time posting).

One of our assignment involves sorting arrays of character strings, these are the key parts of my first draft.

int main()
{
char pals[80][80];
char subString[80];

//Now assume that pals already has 35 sorted rows all filled with 80 characters a piece, I want to find the index of the row where I should stick subString in, so I start at the back and compare the subString to the rows of pals. As I go back I copy the character string in pals[n] to pals[n+1] to free a space for the array that's being inserted.

while (pals > subString) // Need to use a string function, but this is the idea
{
strcpy(pals[i+1], pals);
i--;
}

So in that instance every time you move a character array up 1 index spot, you have to copy 80 individual characters. With enough input, this can be pretty time consuming.

Now the better way...

char * pals = new char[80][80];

Then...

while (pals > subString)
{
pals[i+1] = pals;
i--;
}

Now this way if you call pals, you will get the same array that you would if you weren't using pointers, but the useful part is when you are moving pals[x] up to the next index, instead of having to copy 80 characters, you just copy the address of the first character in the string. This gives you the same end result but is a lot more efficient.

I'm sorry if it came across as confusing, but seeing as how I just found a use for them myself, I'm pretty sure I can't be way over you guys's heads like some of the really smart ones around here :) The syntax of the examples above is terrible, but I was just trying to give a really straightforward example of how those crazy pointers can help.

hmm this is interesting .. however I didn't really get the purpose and the usage :) .. sorry to bring this up but I'm kind of curious

one more thing .. what's the point of using pointers if you were going to specify the range of arrays!
in here
char * pals = new char[80][80];

>< sorry again

This question has already been answered. Start a new discussion instead.