When to use pointers?

I've searched and I didn't find a clear answers. All I can imagine are to use pointers only if you want the data to be deleted (free the memory) after it was used or manipulate a memory which already in use. And I don't know if these are right.
Pointers are necessary for dynamic memory allocation. You may need to dynamically allocate memory if for example you are dealing with a very large set of data, creating a dynamic-length array, etc. Pointers also allow passing data into a function without copying it, like so (although this can also be done through passing by reference):

1
2
3
void setN(int* n){
    *n = 99;
}


This is useful if you need to pass a very large piece of data, such as an object, and don't want the overhead of making a new copy.

There's a lot more to pointers then what I briefly mentioned, but these are a couple examples of why you need them.
They are also useful for passing classes and structs as parameters. Say you had this piece of code in a header file:
1
2
3
4
5
6
7
8
#ifndef MYHEADER
#define MYHEADER

class MyClass;

void funky(MyClass);

#endif 


It looks like you did everything correctly. You prototyped MyClass, so the function afterward can use it. However, you are passing MyClass by value, which requires the compiler to know its size beforehand. In this case, prototyping is not enough. You need to change it to"
1
2
3
4
5
6
7
8
#ifndef MYHEADER
#define MYHEADER

class MyClass;

void funky(MyClass*);

#endif 

Now you are passing via a pointer, which is not the object itself, so the compiler does not need to know the exact size. Now everything is A-Okay and we can all go get some ice cream.
Topic archived. No new replies allowed.