C Cheat Sheet for introduction to Pointers 101:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Program x.y An austere program using C pointers. | |
/* | |
1. num's address: 0x7ffe83ecb46c | |
2. num's value: 13 | |
3. pt's address: 0x7ffe83ecb470 | |
4. pt' size: 8 bytes | |
5. pt's value: 0x7ffe83ecb46c | |
6. value pointed to: 13 | |
7. new num value to: 18 | |
pp = 0x7ffd4799a3b0, ptr = 0x7ffd4799a3b0 | |
*pp = 3, *ptr = 0x7ffd4799a3b0 | |
*/ | |
#include <stdio.h> | |
int main(void) | |
{ | |
int num = 0; // A variable of type int initialized to 0 | |
int *pt = NULL; // A pointer that can point to type int | |
num = 13; | |
printf("1. num's address: %p\n", &num); // Output the address | |
printf("2. num's value: %d\n", num); // Output the value | |
pt = # // Store the address of num in pt | |
printf("3. pt's address: %p\n", (void*)&pt); // Output the address (void pointer = handles any data type) | |
printf("4. pt' size: %zd bytes\n", sizeof(pt)); // Output the size | |
printf("5. pt's value: %p\n", pt); // Output the value (an address) | |
printf("6. value pointed to: %d\n", *pt); // Value at the address (* dereference operator, deferring the pointer) | |
*pt = *pt + 5; | |
printf("7. new num value to: %d\n", num); // Value at the address (* dereference operator, deferring the pointer) | |
int arr[] = { 3, 5, 6, 7, 9 }; | |
int *pp = arr; | |
int (*ptr)[5] = &arr; | |
printf("pp = %p, ptr = %p\n", pp, ptr); | |
printf("*pp = %d, *ptr = %p\n", *pp, *ptr); | |
return 0; | |
} |