int counts = 0;
int *pointer_counts = &counts;
A pointer is a variable that stores the memory address of another variable as its value.
A pointer variable points to a data type (like int
, str
) of the same type, and is created with the *
operator.
When print out the pointer, it would look something like this.
Code:
void main() {
int counts = 0;
int *pointer_counts = &counts;
printf("%p\n", pointer_counts);
}
Output:
0x7ffe5367e044
The value that is being printed is an address of that variable.
We can bring back the value by dereference
We use *
syntax when declaring a variable that will have a pointer assigned to them then assign the variable with another variable name with &
syntax in front of it.
Like this:
int counts = 0;
int *pointer_counts = &counts;
To get value from that memory, we use *
to get value in that memory area.
Not to be confused with creating a pointer. Here's some differences.
- When used in declaration (
int *ptr
), it creates a pointer variable. - When it's not used in declaration (
*ptr
) it act as an dereference operator. - When it's used for calculations (
5 * 3
) it act as multiply.
They are important in C, because they allow us to manipulate the data in the computer's memory. This can reduce the code and improve the performance.
Sometimes you even have to use pointers, for example when working with files or implementing data structures or algorithms.
But be careful. Pointers must be handled with care, since it is possible to damage data stored in other memory addresses.
fuck you zef