tags:

views:

4344

answers:

15
+13  Q: 

Why use pointers?

I know this is a really basic question, but I've just started with some basic C++ programming after coding a few projects with high-level languages.

Basically I have three questions:

  1. Why use pointers over normal variables?
  2. When and where should I use pointers?
  3. How do you use pointers with arrays?

Also, can any of you recommend a good C++ book/ebook?

Thanks in advance.

+13  A: 

Discussed before at this question

Hope that helps!

Doug T.
seems like that addresses what a pointer is not when and why to use them
jk
+3  A: 

Pointers are one way of getting an indirect reference to another variable. Instead of holding the value of a variable, they tell you its address. This is particularly useful when dealing with arrays, since using a pointer to the first element in an array (its address) you can quickly find the next element by incrementing the pointer (to the next address location).

The best explanation of pointers and pointer arithmetic that I've read is in K & R's The C Programming Language. A good book for beginning learning C++ is C++ Primer.

Bill the Lizard
Thats how not why!
Martin York
+2  A: 

In large part, pointers are arrays (in C/C++) - they are addresses in memory, and can be accessed like an array if desired (in "normal" cases).

Since they're the address of an item, they're small: they take up only the space of an address. Since they're small, sending them to a function is cheap. And then they allow that function to work on the actual item rather than a copy.

If you want to do dynamic storage allocation (such as for a linked-list), you must use pointers, because they're the only way to grab memory from the heap.

warren
I think it's misleading to say pointers are arrays. Really, array names are const pointers to the first element of the array. Just because you can access an arbitrary point as if its an array doesn't mean it is... you might get an access violation :)
rmeador
+2  A: 

Because copying big objects all over the places wastes time and memory.

Andrew Medico
And how does pointers help with that? I think a person coming from Java or .Net doesn't know the difference between the stack and the heap, so this answer is pretty useless..
Mats Fredriksson
You can pass by reference. That will prevent copying.
Martin York
+3  A: 
  1. Pointers allow you to refer to the same space in memory from multiple locations. This means that you can update memory in one location and the change can be seen from another location in your program. You will also save space by being able to share components in your data structures.
  2. You should use pointers any place where you need to obtain and pass around the address to a specific spot in memory. You can also use pointers to navigate arrays:
  3. An array is a block of contiguous memory that has been allocated with a specific type. The name of the array contains the value of the starting spot of the array. When you add 1, that takes you to the second spot. This allows you to write loops that increment a pointer that slides down the array without having an explicit counter for use in accessing the array.

Here is an example in C:

char hello[] = "hello";

char *p = hello;

while (*p)
{
    *p += 1; // increase the character by one

    p += 1; // move to the next spot
}

printf(hello);

prints

ifmmp

because it takes the value for each character and increments it by one.

Kyle Cronin
A: 

Another pointer discussion here.

17 of 26
+4  A: 

One reason to use pointers is so that a variable or an object can be modified in a called function.

In C++ it is a better practice to use references than pointers. Though references are essentially pointers, C++ to some extent hides the fact and makes it seem as if you are passing by value. This makes it easy to change the way the calling function receives the value without having to modify the semantics of passing it.

Consider the following examples:

Using references:

public void doSomething()
{
    int i = 10;
    doSomethingElse(i);  // passes i by references since doSomethingElse() receives it
                         // by reference, but the syntax makes it appear as if i is passed
                         // by value
}

public void doSomethingElse(int& i)  // receives i as a reference
{
    cout << i << endl;
}

Using pointers:

public void doSomething()
{
    int i = 10;
    doSomethingElse(&i);
}

public void doSomethingElse(int* i)
{
    cout << *i << endl;
}
trshiv
Probably a good idea to mention that references are safer, in that you can't pass a null reference.
SpoonMeiser
Yeah, that's probably the biggest advantage of using references. Thanks for pointing it out. No pun intended :)
trshiv
+2  A: 

Pointers are important in many data structures whose design requires the ability to link or chain one "node" to another efficiently. You would not "choose" a pointer over say a normal data type like float, they simply have different purposes.

Pointers are useful where you require high performance and/or compact memory footprint.

The address of the first element in your array can be assigned to a pointer. This then allows you to access the underlying allocated bytes directly. The whole point of an array is to avoid you needing to do this though.

Ash
+2  A: 

Here's a slightly different, but insightful take on why many features of C make sense: http://steve.yegge.googlepages.com/tour-de-babel#C

Basically, the standard CPU architecture is a Von Neumann architecture, and it's tremendously useful to be able to refer to the location of a data item in memory, and do arithmetic with it, on such a machine. If you know any variant of assembly language, you will quickly see how crucial this is at the low level.

C++ makes pointers a bit confusing, since it sometimes manages them for you and hides their effect in the form of "references." If you use straight C, the need for pointers is much more obvious: there's no other way to do call-by-reference, it's the best way to store a string, it's the best way to iterate through an array, etc.

Dan
+ 1 for great link, thanks
optician
+1  A: 

One use of pointers (I won't mention things already covered in other people's posts) is to access memory that you haven't allocated. This isn't useful much for PC programming, but it's used in embedded programming to access memory mapped hardware devices.

Back in the old days of DOS, you used to be able to access the video card's video memory directly by declaring a pointer to:

unsigned char *pVideoMemory = (unsigned char *)0xA0000000;

Many embedded devices still use this technique.

MrZebra
A: 

There can be 2 types of "pass" in C,C++ and Java.

  1. Pass by Value.
  2. Pass by reference.

Pointers are required when you want to pass a reference.

I suggest you consult the net or a book to know the difference between the two. This will really help you in understanding why pointers are neccesary.

swapnonil
+11  A: 
  • Why use pointers over normal variables?

Short answer is: Don't. ;-) Pointers are to be used where you can't use anything else. It is either because the lack of appropriate functionality, missing data types or for pure perfomance. More below...

  • When and where should I use pointers?

Short answere here is: Where you cannot use anything else. In C you don't have any support for complex datatypes such as a string. There are also no way of passing a variable "by reference" to a function. That's where you have to use pointers. Also you can have them to point at virtually anything, linked lists, members of structs and so on. Buty let's not go into that here.

  • How do you use pointers with arrays?

With little effort and much confusion. ;-) If we talk about simple data types such as int and char there is little difference between an array and a pointer. These declarations are both the same

char* a = "Hello";
char a[] = "Hello";

You can reach any element in the array like this

printf("Second char is: %c", a[1]);

Index 1 since the array starts with element 0. :-)

Or you could equally do this

printf("Second char is: %c", *(a+1));

The pointer operator (the *) is needed since we are telling printf that we want to print a character. Without the *, the character representation of the memory address itself would be printed. Now we are using the character itself instead. If we had used %s instead of %c, we would have asked prinf to print the content of the memory address pointed to by 'a' plus one (in this example above), and we wouldn't have had to put the * in front:

printf("Second char is: %s", (a+1)); /* WRONG */

But this would not have just printed the second character, but instead all characters in the nextcoming memory addresses, until a null character (\0) were found. And this is where things start to get dangerous. What if you accidentally try and print a variable of the type integer instead of a char pointer with the %s formatter?

char* a = "Hello";
int b = 120;
printf("Second char is: %s", b);

This would print whatever is found on memory address 120 and go on printing until a null character was found. It is not wrong or illegal to perform this printf statement, since a pointer actually is of the type int. Imagine the problems you might cause if you were to use sprintf() instead and assign this way too long "char array" to another variable, that only got a certain limited space allocated. You would most likely end up writing over something else in the memory and cause your program to crash (if you are lucky).

Oh, and if you don't assign a string value to the char array / pointer when you declare it, you MUST allocate sufficient amount of memory to it before giving it a value. Using malloc, calloc or similar. This since you only declared one element in your array / one single memory address to point at. So here's a few examples:

char* x;
/* Allocate 6 bytes of memory for me and point x to the first of them. */
x = (char*) malloc(6);
x[0] = 'H';
x[1] = 'e';
x[2] = 'l';
x[3] = 'l';
x[4] = 'o';
x[5] = '\0';
printf("String \"%s\" at address: %d\n", x, x);
/* Delete the allocation (reservation) of the memory. */
/* The char pointer x is still pointing to this address in memory though! */
free(x);
/* Same as malloc but here the allocated space is filled with null characters!*/
x = (char *) calloc(6, sizeof(x));
x[0] = 'H';
x[1] = 'e';
x[2] = 'l';
x[3] = 'l';
x[4] = 'o';
x[5] = '\0';
printf("String \"%s\" at address: %d\n", x, x);
/* And delete the allocation again... */
free(x);
/* We can set the size at declaration time as well */
char xx[6];
xx[0] = 'H';
xx[1] = 'e';
xx[2] = 'l';
xx[3] = 'l';
xx[4] = 'o';
xx[5] = '\0';
printf("String \"%s\" at address: %d\n", xx, xx);

Do note that you can still use the variable x after you have performed a free() of the allocated memory, but you do not know what is in there. Also do notice that the two printf() might give you different addresses, since there is no guarantee that the second allocation of memory is performed in the same space as the first one.

Tooony
Your example with 120 in it is wrong. It's using %c not %s so there's no bug; it merely prints the lowercase letter x. Moreover, your subsequent claim that a pointer is type int is wrong and very bad advice to give to a C programmer inexperienced with pointers.
R..
@R.. the %c has been changed to %s
Kelly French
-1 You started well but the first example is wrong. No, it's not the same. In the first case `a` is a pointer and in the second case `a` is an array. Did I mention it already? It's not the same! Check for yourself: Compare sizeof(a), try to assign a new address to an array. It won't work.
sellibitze
`char* a = "Hello";` and `char a[] = "Hello";` are not same, they are quite different. One declares a pointer the other an array. Try a `sizeof` and you see the differnce.
tristopia
A: 

In java and C# all the object references are pointers, the thing with c++ is that you have more control on where you pointer points. Remember With great power comes grand responsibility.

Marioh
A: 

I can't answer the question because it will get long. But, I want to tell one important thing. Pointer and Array are different.

Please see here.

A: 

pointers are used because performance is increased in allocation and retreival of data from dynamic heap area.

vilakshan