Pointers are a little complicated.
When you write
int num = 10;
you are declaring a variable that holds an integer, and assigning it a value: 10
You can do maths with that, and print it if you want:
int num = 10;
num = num + 100;
printf("num = %u\n", num);
When you write
int* ptr = #
you are declaring a variable that holds a pointer to an integer, and assigning it a value: the address of a variable.
You can then use that pointer to change the value of the variable it points to by using the * prefix to dereference the pointer:
int num = 10;
int *ptr = #
*ptr = *ptr + 100;
printf("num = %u\n", num);
This has the same effect as the original code, but you are "getting at the value" via a different route.
But
ptr
is not the same as
num
: if you change
ptr
it doesn't affect the value at all:
int num = 10;
int *ptr = #
ptr = ptr + 100;
printf("num = %u\n", num);
Will still print "10" because you changed the variable that points to memory, not the memory itself.
That's important, because later when you meet arrays, you will find pointers pretty handy:
int num[10];
for (int i = 0; i < 10; i++)
{
num [i] = i;
}
int *ptr = #
while (*ptr < 5)
{
*ptr = *ptr + 100;
ptr = ptr + 1;
}
for (int j = 0; j < 10; j++)
{
printf("%u ", num[j]);
}
And when you dereference a pointer, what you get is not a pointer - it's the type of variable the pointer points to.
So saying this:
int num = 10;
int *ptr;
ptr = #
Will give you an error because
*ptr
is an integer and you are trying to store an address in it.
int num = 10;
int *ptr = #
Doesn't give an error because the
int *
part is the declaration of the type of
ptr
rather than a dereference.
Make sense?