Pointer Arithmetic
One of the strengths of pointers is that you can do basic arithmetic with it. Though arithmetic may originally mean mathematical operators; for pointers, only addition (and subtraction) are defined. Continue reading
One of the strengths of pointers is that you can do basic arithmetic with it. Though arithmetic may originally mean mathematical operators; for pointers, only addition (and subtraction) are defined. Continue reading
New C/C++ programmers often have this confusion that all arrays are pointers. Well… they’re kinda, sorta, but not really. Let’s consider the following code:
1 2 3 4 |
char arr[5] = {'H','e','l','l','o'}; char *p = &arr[0]; printf("%c\n", p[2]); // l printf("%c\n", *arr); // H |
Try compiling the code snippets using Coding Ground.
The pointer p points to the first character of arr. Remember that the index operator ([]) is automatically converted to addition then dereference.
1 |
p[2]; // same as *(p + 2) |
Note: 2[p] would be evaluated to *(2 + p) giving us the same result as p[2]. It’s bad practice to use that form even if it works.
And dereferencing arr is similar to getting the first element
1 |
*arr; // same as *(arr + 0) which is arr[0] |
So when do arrays and pointers differ?
As a continuation to the discussion on Purpose of Pointers to Functions, let’s step up the complexity and have an array of function pointers. This time, we’ll use C++ because we’ll need the inheritance for demonstration 🙂
What’s the purpose of having an array of function pointers?
In a previous post, I mentioned something about pointers to functions. Why would anyone need pointers to functions? In C/C++, they’re called function pointers. They also exist in other languages but the implementations are slightly different. In C#, they’re called delegates. Many OOP languages have interfaces with overrideable methods. In others, there’s the concept of lambda (anonymous) functions.
One common application of function pointers are Event Handlers. Event handlers are quite straight forward. Assign a function as an event handler and when that event is triggered, execute the corresponding function. See W3Schools for more info on JavaScript Event Handling. These functions are referred to as Callbacks.
In C#, they allow adding/subtracting of delegates. Adding a delegate simply adds that method to the list of methods that will be executed, one by one in the order they were added, when the event is triggered. Subtracting removes that method from the list. This allows having multiple listeners to a single event. See MSDN for more information.
What’s the point of pointers to functions?