What is the purpose of a pointer in programming?

The full question ended with: “Why not access the variable directly?

It depends on what you mean by “access the variable directly.” In Algol derived languages (like C, C#, C++, Pascal, Ada), the way to access a variable directly is through pointers. Java is a bit different. In Algol derived languages, you can pass a pointer to a variable in a call to a function or method. Then, whatever you do to that variable in the called function or method will alter the variable you passed by pointer in the calling code. In the Algol group of code, this is called “pass by reference” which means something totally different in Java.
FORTRAN started using pass by pointer, without actually stating what it was doing, in order to save space within the program. I learned this the hard way by passing the number “2” to a subroutine (same as a function or a method) and then changing the value of that variable in the subroutine. Since 2 in FORTRAN is stored as a pointer to the value “2” every time I would use “2” after that call, the actual value used was to what the subroutine set it.

One of the purposes of a pointer is to allow other routines to modify the value contained in the memory location(s) referenced by the pointer. As mentioned earlier, Java does not allow pointers. However, there are methods documented, for example in “How to do the equivalent of pass by reference for primitives in Java” to get around this rule for this one purpose.

In the “old” days of programming, before programmers were given a “sandbox” within to work, pointers could point to actual physical locations in memory instead of just locations relative to where your sandbox is located. With these pointers people could (and did) go in and modify the operating system on the fly. Something I do not recommend doing. This is one of the reasons Java was developed to not allow pointers.

This entry was posted in Ada, Algol, C, C#, C++, FORTRAN, Java, Pascal, Software and tagged , , , . Bookmark the permalink.

I would enjoy hearing from you.

This site uses Akismet to reduce spam. Learn how your comment data is processed.