// Pantea Aria // introduction to pointers #include int main() { int x = 90; // what is the address (or reference) of x printf ("the address of x in memory is %p\n", &x); printf ("the value of x is %d\n", x); // I can store the address of x in another variable // that variable is called a pointer int *ptr; // & is called reference/address operator ptr = &x; printf("the value of ptr is %p\n", ptr); // dereference // having access to where the pointer is pointing to int y = *ptr; //same as int y = x; printf ("y is the value of where ptr is pointing to %d\n", y); // change the value of x indirectly // directly means e.g x = 100; *ptr = 100; // same as x = 100; not as y = 100; printf("the new value of x is %d\n", x); printf ("y is %d\n", y); y = *ptr; // y will be 100 return 0; } // When we declare a variable in C, where does it live? // (This leads to the idea of memory locations.) // What do you think this operator & does in C? // int x = 10; // printf("%p\n", &x); // What does this print? shows some hex value // Can a variable store another variable’s memory address? // What is the value of this variable, and what is its address? // int a = 5; value is 5, some hex value &a with %p // How can we print the address of a? printf ("%p", &a); // value: printf ("%d", a); // Can we store this address in another variable? yes, I must declare a pointer // If we store the address of a in a variable, how can we use it to get the value back? // int a = 10; // int *p = &a; // *p = 20; // printf("%d\n", a); // What will this print? // Predict the output and explain: // int x = 3; // int y = 4; // int *p = &x; //declare a pointer to x, p has the address of x, referencing // *p = y; //deferencing // printf("%d\n", x); // What’s the difference between p = &x; and *p = x;? // What is happening here? // int a = 100; // int *ptr1 = &a; // int *ptr2 = ptr1; // printf("%d\n", *ptr2);