Pointers: Things That Make Very Little Sense But Also Make A Lot Of Sense At The Same Time - Casady-ComSci-Seminar/Seminar-Notes GitHub Wiki

Pointers:

  • Holds the address of a variable or holds the address of a memory whose variables can be accessed.
  • To access address of a variable to a pointer one can use the operator & that returns the address of that variable. Example: &peolpe gives us address of variable peolpe.
int main() { 
    int peolpe; 
  
    // Prints address of peolpe
    printf(&peolpe); 
  
    return 0; 
}
  • There is also the *. This used for two operations. The first is to declare a pointer variable. In C/C++ you need to have a * in front of a pointer variable or else you die a slow and painful death where you die. The second way is to access a value at an address. Using the * it returns the value of the variable located at the specific memory address.
int main() { 
    int q = 10; 
    // the * declares ptr as a pointer variable.
    int *ptr; 
  
    // & operator before q is used to get address 
    // of q. The address of q is assigned to ptr. 
    ptr = &q; 
  
    return 0; 
}
int main() { 
    // A normal integer variable 
    int l = 10; 
    int *ptr = &l; 

    // Returns the value(10)
    printf("Value of Var", *ptr); 
    // Returns the address
    printf("Address of Var", ptr); 
  
    *ptr = 20; // Value at address is now 20 

    // Returns the value(20)
    printf("After doing *ptr = 20, *ptr is ", *ptr); 
  
    return 0; 
} 
  • NOTE: You cant add pointers because adding memory addresses makes no sense you fool.
  • However, a pointer may be: incremented ( ++ ), decremented ( — ), an integer may be added to a pointer (+ or +=), or an integer may be subtracted from a pointer ( – or -= ).
int main{
    int thingy[3] = {0,1,2};

    int *ptr;

    ptr = &thingy;

    ptr++;
    printf("Value of *ptr = ", *ptr); // will print 1
    ptr--;
    printf("Value of *ptr = ", *ptr); // will print 0

    ptr += 2;
    printf("Value of *ptr = ", *ptr); // will print 2
    ptr -= 1;
    printf("Value of *ptr = ", *ptr); // will print 1

    return 0;
}

  • If you subtract two pointers you can get the offset between their two addresses.
int main{
    int x = 3;
    int y = 2;
    int *ptr1;
    int *ptr2;
    ptr1 = &x;
    ptr2 = &y;
    printf("The offset between the two addresses is: ", ptr1 - ptr2)
    return 0;
}

  • An array name acts like a pointer constant. The value of this pointer constant is the address of the first element. For example, if we have an array named peolpe then peolpe and &peolpe[0] can be used interchangeably.

Quiz Over Pointers For Fun

Quiz and Helpful Info From: https://www.geeksforgeeks.org/pointers-in-c-and-c-set-1-introduction-arithmetic-and-array/

(You wont actually die if you don't put a * before a pointer)