Just a quick question that I am slightly puzzled by:
Pointers as function arguments; if I was to write something like this: blah(int *number)
I am giving it the memory address of number, not actually transferring number. Am I correct? If so, then I don't understand, isn't '*' meant to be pointing to the data itself, so shouldn't that be accepting the thing actually being pointed to? Also, why, when I call blah, do I have to specify the memory address of what I am trying to pass to the function, since that is not what it is receiving.
I am giving it the memory address of number, not actually transferring number. Am I correct?
Not quite. void blah(int *number);
This means blah is a function that accepts a pointer to an int. When the function is called, the pointer you pass in is copied, and that copy is handed to the function.
This syntax int*
means "an object of type pointer-to-int". That's what you've put in your function prototype above.
This syntax x (where x is a pointer)
means "the actual pointer x"
and this syntax *x
means "the object that x is pointing to"
Here's a similar thing done with just a plain int:
if I was to write something like this: blah(int *number)
I am giving it the memory address of number, not actually transferring number. Am I correct?
Not quite. number is the name of the parameter, and it's type is "a pointer to an int". The name you've given it is misleading and re-enforcing the confusion, let's call it ptr.
When blah is called, you have to specify the address of an int. For example:
#include <stdio.h>
int a = 3, b = 4;
void SetToZero(int *ptr) // ptr is the address of an int
{
if (ptr == &a)
printf("SetToZero was passed the address of a\n");
elseif (ptr == &b)
printf("SetToZero was passed the address of b\n");
else
printf("SetToZero was passed some unrecognised address\n");
*ptr = 0; // assign zero to the int by dereferencing the pointer
}
int main()
{
printf("a=%d, b=%d\n", a, b);
SetToZero(&a); // pass the address of a to SetToZero
printf("a=%d, b=%d\n", a, b);
SetToZero(&b); // pass the address of b to SetToZero
printf("a=%d, b=%d\n", a, b);
return 0;
}