This worksheet is intended to show the relationship between array names, subscripts, and pointer arithmetic. It may be helpful (but not required) to use a sheet of graph paper to represent where the variable values are stored (their addresses or storage locations). It is easier to understand the relationship if you can visualize how the information is stored.
SET-UP
void main() { int int_ary[10]={2,4,6,8}; // array of 10 integers char chr_ary[11]; // array of 11 characters, // room for 10 useable characters // and the null terminator . . . }
Assume that the space reserved for the
integer array starts at storage location 2000.
Assume that the space reserved for the character array starts at
storage location 1600.
PART 1
If you have been writing out the storage locations, you should have something similar to the charts below.
location | 1000 | 1001 | 1002 | 1003 | 1004,1005 | 1006,1007 | 1008 | 1009 |
value | 1600 | 2000 | ||||||
name | chr_ary | int_ary |
location | 1600 | 1601 | 1602 | 1603 | 1604 | 1605 | 1606 | 1607 | 1608 | 1609 | 1610 |
value | c | o | m | p | u | t | e | r | \0 | ??? | ??? |
name * | [0] | [1] | [2] | [3] | [4] | [5] | [6] | [7] | [8] | [9] | [10] |
* names used are chr_ary[subscript]
location | 2000,2003 | 2004,2007 | 2008,2011 | 2012,2015 | 2016,2019 |
value | 2 | 4 | 6 | 8 | 0 |
name | int_ary[0] | int_ary[1] | int_ary[2] | int_ary[3] | int_ary[4] |
location | 2020,2023 | 2024,2027 | 2028,2031 | 2032,2035 | 2036,2039 |
value | 0 | 0 | 0 | 0 | 0 |
name | int_ary[5] | int_ary[6] | int_ary[7] | int_ary[8] | int_ary[9] |
PART 2
Check the answers to PART 1 before
continuing. You need to understand #4-8 inorder to do PART 2.
Assume the following line of code has been executed.
strcpy(chr_ary, "computer");
The values in the integer array have not changed.
Determine the value of each expression below.
1. chr_ary chr_ary+0 *chr_ary *(chr_ary+0) 1600 1600 'c' 'c'
2. chr_ary+1 *chr_ary+1 *(chr_ary+1) 1601 'd' 'o' 'c' + 1 = 'd'
3. int_ary *int_ary *(int_ary+0) 2000 2 2
4. int_ary+1 *int_ary+1 *(int_ary+1) int_ary[1] 2004 3 4 4 (2000 + 1 int space = 2000 + 4 bytes)
5. *(chr_ary+3) chr_ary[3] chr_ary+3 'p' 'p' 1603
6. chr_ary chr_ary[0] *chr_ary &chr_ary[0] 1600 'c' 'c' 1600 (location of the first element)
7. int_ary int_ary[0] *int_ary &int_ary[0] 2000 2 2 2000
8. &int_ary[0] &int_ary *int_ary+0 int_ary 2000 1006 2 2000
9. int_ary[2] *(int_ary+2) &int_ary[2] int_ary+2 6 6 2008 2008
10. int_ary+10 int_ary[10] *(int_ary+10) 2040 garbage garbage (from the next 4 bytes after the array)