Yeah, I'm one of those self-taught (or in this case, self-teaching) programmers. And since C is the first language I'm really going into, I've no background to base my questions on to build a bridge and understand it better.
Anyways, my question is...pointers. Up until now, I've been fine. I haven't really been able to find a real good begginer explanation for them. Can anyone point (no pun intended ;)) me in the right direction for a good explanation of them?
A pointer is a variable with a data type, just like an int or a char. But instead of containing a value like 5 or 'a', a pointer variable contains an address in memory. That's as simple as it gets, how pointers are used is a bit more complicated but not much.
int x = 5;
x is now a container that can hold a value from INT_MIN to INT_MAX, this range varies from system to system. x has two properties, a value and an address. The value is the usable number that you place in x, 5 in this case. The address is where x resides in memory and is most commonly used with pointers. Because a pointer is a variable that holds an address, the following works nicely:
int x = 5;
int *p = &x;
p is a pointer variable of the int data type, and it is initialized to the address of x, the & operator returns the address of the variable it is used on. At this point, p can be used everywhere x can simply by dereferencing the pointer. When you dereference a pointer it means to retrieve the value contained at the address contained in the pointer.
int y = *p;
The variable y would now contain the value 5 because p points to the address of x which contains the value 5. The * operator tells the compiler to dereference a variable. If you don't dereference a pointer then the value you will get is an address.
Now, this is where pointers become truly useful. When you have a variable that points to another variable, you can change that variable through the pointer. When passing a variable to a function, the function gets a copy of that variable, so the original will not be changed. If you want to change the original then you can pass a pointer to that variable. A copy is made of the pointer, but it still points to the same address and you can change the original object.
This is also a very nice feature if you need to pass large objects to a function. Making copies of those objects is wasteful, it is far more efficient to pass a little pointer instead.
Since a pointer holds an address, and all objects in C have addresses ( not all, but bear with me ), you can also use a pointer to hold the address of a function. Pointers to functions are not basic, so I'll not go any further into them, but you can easily see the power that pointers have, right?
Thank you again Prelude, it cleared up a bit of my fogginess. :)