GO BACK

What I'm learning in C: Pointers

DISCLAIMER: This isn't organized I just ramble about stuff I learned randomly as a newcomer to programming, this isn't serious or a lesson. Writing stuff like i'm explaining it to someone makes it easier for me to remember concepts and clear out thoughts in my head, but I don't do tutorials lol. Though it's cool if you learned something. I guess this is kinda useless but I'll try to talk about tech stuff in a more personal way in the future to make it more interesting.

Recently I dived into a concept that sounds pretty scary to new programmers since it dabbles in memory adresses. So far though it looks quite easy. Pointers are from what I understood variables where you store memory addresses, written like a normal variable but starting with *. Then the pointer name without * is the memory address, and with the * it's the the value stored. You can also see the memory location of a variable by writing & before it's name. (I finally understood why scanf needs & before the variable name, it needs to know where to store in the memory location lol). Neat concept, I'm going to try to learn it more in depth.

How it works:


    #include <stdio.h>
   
    int main()
    {
        int i;
        int *ptr_to_i;

        ptr_to_i = &i;

        printf("The value of i is %d\n", i);
        printf("The memory location of i is %d\n", &i);
        printf("The memory location of i is %d\n", ptr_to_i);
        printf("The value of i is %d\n", *ptr_to_i);
    } 
    

Here I made the i integer and the ptr_to_i pointer, and set i to be stored in the memory address the pointer is pointing to. By testing these printfs, you can see which syntax prints the stored memory address and which one prints the stored value.