Hey all. Recently i've run across a few problems with rebinding (changing) POINTERS in functions in C while sorting strings. What follows is an attempt to clarify some possible confusion with passing by reference in C for those somewhat new to the language. Now, there's a difference in changing the
variable that the pointer points to and changing what the
pointer points to. Got that? For example, look at this:
Code: Select all
#include <stdio.h>
void ch_var(int *ptr);
int main()
{
int num = 5;
printf("Before the change: %d\n", num);
ch_var(&num);
printf("The variable num is equal to: %d\n", num);
return 0;
}
void ch_var(int *ptr)
{
*ptr = 10;
}
The above code is simple. It just switches the value in the
variable pointed to by the pointer. But in order to change the address that the pointer points to, inside a function other than main, you have to pass the
pointer itself by reference. Take the following as an example:
Code: Select all
#include <stdio.h>
void ch_ptr(int *ptr);
int main()
{
int n_one = 10;
int *n_ptr;
n_ptr = &n_one;
ch_ptr(n_ptr);
if(n_ptr == NULL)
printf("n_ptr has been set to NULL.\n");
else
printf("n_ptr is still: %d\n", *n_ptr);
return 0;
}
void ch_ptr(int *ptr)
{
ptr = NULL;
}
The above still does not rebind the pointer because it's not passed by reference. Keep in mind that
everything in C is passed by value by default, including pointers. To change that, we do this:
Code: Select all
#include <stdio.h>
void ch_ptr(int **ptr);
int main()
{
int n_one = 10;
int *n_ptr;
n_ptr = &n_one;
ch_ptr(&n_ptr);
if(n_ptr == NULL)
printf("n_ptr has been set to NULL.\n");
else
printf("n_ptr is still: %d\n", *n_ptr);
return 0;
}
void ch_ptr(int **ptr)
{
*ptr = NULL;
}
First, we change the prototype and the definition of 'ch_ptr' to take a
pointer to pointer to int. And when calling the function in main(), we pass the
address of the pointer variable itself. This allows pass the pointer by reference and change it in a function. To change it's value (address pointed to), we do this (but note that NULL is not a valid address to point to in C, it's just used for an example of modifying the ptr):
Why do we use an asterisk on the pointer you ask? Well, in 'ch_ptr', you're using
two levels of indirection. So, To modify it, we dereference it to get to the pointer since when the function is entered, 'ptr' contains the address of the pointer that points to the address of the variable! (confused yet?). To verify the change, when back in main we test it against null, and find that in fact it is changed! That's all folks.
Thanks for reading. Happy Hacking =]