=====Exercise: Pointers==== ====Background==== When we think back on arrays, we notice there are two properties for each element: * the element index (address) * the element contents So, you've got memory, and you've got variables allocated in that memory. The array sets up its own "addressing" scheme, using the array indices as an offset to that memory address. Pointers utilize a similar concept. They represent an address in memory and can be used when dealing with stored values. The difference is- the pointers don't contain any data themselves, but they point to something that does. ** *aPtr** in C refers to the contents of the address of whatever **aPtr** happens to be pointing to. **&z** refers to the address in memory where the variable **z** is located (if the data type occupies more than one byte, assume it returns the highest order byte's address). ====Exercises==== Here's our memory (this time in Hex, just like it would be on the computer):
myint
00
0x00

0C
0x01

3A
0x02

FF
0x03
c1
'A'
0x04
value
00
0x05

01
0x06
c2
'4'
0x07
data[4]
00
0x08

00
0x09

00
0x0A

00
0x0B

00
0x0C

00
0x0D

00
0x0E

00
0x0F


0x10


0x11


0x12


0x13


0x14


0x15


0x16


0x17


0x18


0x19


0x1A


0x1B


0x1C


0x1D


0x1E


0x1F
For the purposes of this exercise: * We are assuming all the data for this exercise falls in the range of this memory. * Each address represents a group of 8-bits, or 1 byte. * Green blocks are integers, Red are characters, and Light Blue are short integers. * Top of each square contains variable name (at least in most significant byte) * Middle of each square contains any data (8-bits) * Bottom of each square contains the address in hexadecimal. Our computer in this scenario has addresses of **0x00-0x1F**, for a grand total of 32 bytes of memory. The above diagram is the result of the following variable declarations (in this order): int myint; char c1 = 'A'; short int value = 1; char c2 = '4'; short int data[4]; So, explore the following: ===Scenario A=== If we do the following: char *cPtr; cPtr = &c1; printf("Contents are: %c\n", *cPtr); What is displayed to the screen? ===Scenario B=== Adding to the previous: *cPtr = c2 + 1; printf("Contents are: %c\n", *cPtr); What is displayed to the screen now? ===Scenario C=== Using pointer arithmetic, how would we place a 73 inside the 3rd element of the data[] array? ===Scenario D=== Based on what we did in scenarios A and B, let's do this: cPtr = &c2; printf("Contents are: %c\n", *cPtr); What will get output to the screen? ===Scenario E=== If we were to print out the address generated by &myint, what would it be? ===Scenario F=== If we did the following: int *iPtr; iPtr = &myint; printf("Value is: %d\n", *iPtr); What integer value gets output to **STDOUT**?