Sams Teach Yourself C in 21 Days

(singke) #1
If all three of these pointers have the same value, what is the practical difference between
them in terms of your program? Remember from Day 9 that the C compiler knows what
a pointer points to. To be more exact, the compiler knows the size of the item a pointer is
pointing to.
What are the sizes of the elements you’ve been using? Listing 15.2 uses the operator
sizeof()to display the sizes, in bytes, of these elements.

LISTING15.2 multsize.c. Determining the sizes of elements
1: /* Demonstrates the sizes of multidimensional array elements. */
2:
3: #include <stdio.h>
4:
5: int multi[2][4];
6:
7: int main( void )
8: {
9: printf(“\nThe size of multi = %u”, sizeof(multi));
10: printf(“\nThe size of multi[0] = %u”, sizeof(multi[0]));
11: printf(“\nThe size of multi[0][0] = %u\n”, sizeof(multi[0][0]));
12:
13: return 0;
14: }

The output of this program (assuming that your compiler uses four-byte integers) is as
follows:
The size of multi = 32
The size of multi[0] = 16
The size of multi[0][0] = 4
Note that on different machines the size values may be different.
The size of multi = 32
The size of multi[0] = 16
The size of multi[0][0] = 4
If you’re running an a 32-bit operating system, your output will most likely be 32 , 16 ,
and 4. This is because a type intcontains four bytes on these systems. On older 16-bit
systems you may get the results of 16 , 8 , and 2.
Think about these size values. The array multicontains two arrays, each of which con-
tains four integers. Each integer requires four bytes of storage. With a total of eight inte-
gers, the size of 32 bytes makes sense.
Next,multi[0]is an array containing four integers. Each integer takes four bytes, so the
size of 16 bytes for multi[0]also makes sense.

392 Day 15

INPUT

OUTPUT

ANALYSIS

25 448201x-CH15 8/13/02 11:13 AM Page 392

Free download pdf