Skip to content

Instantly share code, notes, and snippets.

@timelessnesses
Last active July 31, 2023 11:50
Show Gist options
  • Save timelessnesses/e801cb51716cfe0d15340b7201297bc5 to your computer and use it in GitHub Desktop.
Save timelessnesses/e801cb51716cfe0d15340b7201297bc5 to your computer and use it in GitHub Desktop.
C pointer.

C pointer

What is pointer in C?

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

Creating A Pointer

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;

Dereference

To get value from that memory, we use * to get value in that memory area.

NOTE

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.

What's cool about pointer?

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.

@timelessnesses
Copy link
Author

fuck you zef

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment