C Programming – Benefits of Pointers

c++pointers

I recently developed an interest in C programming so I got myself a book (K&R) and started studying.

Coming from a University course in Java (basics), pointers are a totally new chapter, and from what I read online it's a rather difficult concept to get your head around. Before getting to the pointer chapter I was under the impression that pointers are a major part of C and provide great benefits.

Upon reading the chapter and getting a basic idea of what pointers are and how they work, the benefits are not obvious to me.

For example (please correct me if I got this totally wrong) in the introduction of pointers in the K&R book it says that since we call by value, when passing a variable in a function call we pretty much pass a copy of the variable for the function to handle and therefore the function can't do anything to the original variable and we can overcome this with pointers.

In a later example that uses a char pointer, the book says that incrementing the char pointer is legal since the function has a private copy of the pointer. Aren't 'private copies' a reason to use pointers instead?

I guess I'm a bit confused on the whole use of pointers. If asked I can use pointers instead of using array subscripts for example, but I doubt this is the main use of pointers.

Linux and Open source programming was the main reason I got into C. I got the source code of a C project to study (Geany IDE) and I can see that pointers are used throughout the source code.

I also did a bit of searching in the forums and a found a couple of posts with similar questions. An answer was (I quote):

If you don't know when you should use pointers just don't use them.

It will become apparent when you need to use them, every situation is different.

Is it safe for me to avoid using pointers at the time being and only use them in specific situations (where the need for pointers will be apparent?)

Best Answer

One benefit of pointers is when you use them in function arguments, you don't need to copy large chunks of memory around, and you can also change the state by dereferencing the pointer.

For example, you may have a huge struct MyStruct, and you have a function a().

void a (struct MyStruct* b) {
   // You didn't copy the whole `b` around, just passed a pointer.
}
Related Question