Let’s learn about pointers, one of the most important things in C language.

1. Concept

This is a variable that stores a memory address.

Each variable has a unique address somewhere in memory.

A pointer points to the address and indirectly accesses or changes the value of the target variable.

2. Declaration and initialization

int x = 42;
int *p;      
p = &x;
  • int *p; : p is a pointer to int
  • &x: address of x (address operator)
  • Must be initialized to a valid address after declaration

3. Backreference, assignment

int y = *p;  
*p = 100;
  • *p: actual value of memory pointed to by p
  • int y = *p; → The value of x is copied to y
  • *p = 100; → The value of x changes to 100\

4. Example

#include <stdio.h>

int main(void) {
    int number = 5;
    int *p = &number;
    printf("Initial value: %d\n", number);
    *p = 10;
    printf("Updated value: %d\n", number);
    return 0;
}
  • #include <stdio.h> Declare to use standard input/output functions.
  • int main(void) { Defines the main function, which is the starting point of the program.
  • int number = 5; Create an integer variable named number and store the value 5 in it.
    • A number box is created in memory, and the number 5 is placed inside it.
  • int *p = &number;
    • int *p; means ‘pointer to an integer’.
    • &number gets the memory address of the number box. So pointer p remembers the location of the number box.
  • printf("Initial value: %d\\n", number);
    • Prints the value of number in place of %d.
    • At this time, the output result will be the initial value: 5.
  • *p = 10;
    • *p means the actual value of the box pointed to by pointer p.
    • If you substitute 10 here, the value in the number box changes from 5 to 10.
  • printf("Updated value: %d\\n", number);
    • Prints number again.
    • This time, since the value was changed with a pointer, the value after change: 10 is displayed.
  • return 0; Close the program normally.
  • } Marks the end of the main function.

Because it is so difficult and important that it can be considered the most important part.

I think it would be a good idea to watch it several times and try it yourself.

Let’s try to understand as much as possible.