Notes 01/13/2020 > Review from COEN10 # Pointers int x; x = 6; int *px; px = &x; - The pointer `*px` is "pointing" to the memory address where x is located (`&x`) - The pointer must be assigned a data type (in this case `int`) that matches the memory type that it is pointing to ``` x = 5; *px = 1 printf("%d", x); ``` - The code above will print `1` because `*px` (the value in the memory address that px is pointing to) was changed to 1, so x was changed to 1 - You can change where the pointer is pointing to: `px++` changes the pointer to point to the next memory address - This is useful when dealing with arrays: ``` int x[5] = {1, 2, 3, 4, 5} int *px; px = &x[0]; //can also be written px = x printf("%d", *px); px++; printf("%d", *px); ``` The code above would print `1` and then `px++` would move the pointer to point to `x[1]` and the second number printed would be `2` int i; px = &x[0]; for(i = 0; i < 5; i++){ printf("%d\n", *px); px++; } The code above would result in: 1 2 3 4 5 Another Example: int x = 2, y = 2; int *p, *q; p = &y; q = &y; //(p == q) is false (comparison of addresses) //(*p == *q) is true (comparison of values) Visual Representation of Memory: int x[7] = {1, 2, 3, 4, 5, 6, 7}; int *px; px = &x[0]; `x[]` in memory | 1 | 2 | 3 | 4 | 5 | 6 | 7 | | - | - | - | - | - | - | - | | px | | | | | | | px+=3; | 1 | 2 | 3 | 4 | 5 | 6 | 7 | | - | - | - | - | - | - | - | | | | | px | | | | --- # Using Pointers with Strings Example: char my_string[] = "String!" char *p = my_string //Single line pointer definition. can also be written *p = &my_string[0] Visual Representation of `my_string[]` in memory: | S | T | R | I | N | G | ! | \0 | | - | - | - | - | - | - | - | - | | p | | | | | | | | We can print the string like this: //don't need i while(*p != '\0'){ printf("%c", *p); p++; } The above code would print `STRING!` --- # Pointers and Functions - A function can also receive an array as an argument in the form of a pointer - For Example: ``` void my_function(char *c){ ... } ``` - The function would receive a memory address pointing to a char. It would be beneficial to pass a memory address pointing to a string. - Let's flesh-out the example: ``` void my_function(char *c){ printf("%s\n", *c); c++; printf("%s\n", *c); } ``` - Let's say we pass a memory address `&my_string[0]` and my_string is defined as `char my_string[] = "Hello World"` - The code would output: ``` Hello World ello World ``` --- [-> Notes 01/15](01-15.md)