Pointers...

I've read dozens of tutorials, i get how pointers are initialized etc. But i just don't get WHY you would want to use them and how, And whats the difference if you don't. On the flip side i DO understand references.
Can someone help out a bit?
References are actually pointers. You just don't have to type all the *s and &s to use them.

The primary purpose of a pointer is to access dynamic data. For example, say you wish to read a WAV file into memory (for example, the ever obnoxious C:\WINDOWS\Media\tada.wav) and do some processing on it.

You could just declare an array of

C:\WINDOWS\Media>dir tada.wav
Volume in drive C is Ceres
Volume Serial Number is D000-0000

Directory of C:\WINDOWS\Media

08/29/2002 07:00 AM 171,100 tada.wav
1 File(s) 171,100 bytes
0 Dir(s) <censored> bytes free

bytes:
unsigned char file_data[ 171100 ];

But what if you want to be able to load any WAV file (as specified by the user), or some really, really big file? For that you'll need to use malloc() or new to get the memory:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
void* load_file( const string& filename, streamsize& filesize )
  {
  char* result;

  ifstream inf( filename.c_str(), ios::binary );
  if (!inf) return NULL;

  inf.seekg( 0, ios::end );
  filesize = inf.tellg();
  inf.seekg( 0, ios::beg );

  result = new (nothrow) char[ filesize ];
  if (result)
    {
    inf.read( result, filesize );
    }
  inf.close();

  return (void*)result;
  }

This is, obviously, a cheesy example, but hopefully it demonstrates the idea well enough.

Hope this helps.

[edit] I'm still learning to spell, apparently... [/edit]

[edit 2] Actually, references can be optimized much more readily than pointers too... [/edit]
Last edited on
Why would i need to use malloc or new though? couldnt i just say char result?
char result; allocates space for exactly one char. Duoas' point is that sometimes you don't know the number of bytes you need at compile time. Sometimes it is a runtime decision, and that is when you need to use dynamic memory allocation.

Another use for pointers is to extend the lifetime of variables. Variables "go away" when the scope in which they are declared exits. For example,

1
2
3
4
void foo() {
   int x;
   // stuff here
}


The variable x is created when the function is entered and is destroyed when it exits. What if you need x to stay around longer? (Ok, one way of accomplishing this is simply to return x to the caller. In this simple of an example, that is probably sufficient. But there are more complex examples where returning the variable either isn't appropriate or not possible).

That's when you use new (C++) or malloc (C). You can then delete (C++) or free (C) the variable when you no longer need it.

Oh wow, that just made it 99% clearer, thanks man!
Topic archived. No new replies allowed.