Sizeof - Need For sizeof

Need For sizeof

In many programs, there are situations where it is useful to know the size of a particular datatype (one of the most common examples is dynamic memory allocation using the library function malloc). Though for any given implementation of C or C++ the size of a particular datatype is constant, the sizes of even primitive types in C and C++ are implementation-defined (that is, not precisely defined by the standard). This can cause problems when trying to allocate a block of memory of the appropriate size. For example, say a programmer wants to allocate a block of memory big enough to hold ten variables of type int. Because our hypothetical programmer doesn't know the exact size of type int, the programmer doesn't know how many bytes to ask malloc for. Therefore, it is necessary to use sizeof:

/*pointer to type int, used to reference our allocated data*/ int *pointer = malloc(10 * sizeof (int));

In the preceding code, the programmer instructs malloc to allocate and return a pointer to memory. The size of the block allocated is equal to the number of bytes for a single object of type int, multiplied by 10, ensuring enough space for all 10 ints.

It is generally not safe for a programmer to presume to know the size of any datatype. For example, even though most implementations of C and C++ on 32-bit systems define type int to be 4 bytes, the size of an int could change when code is ported to a different system, breaking the code. The exception to this is the char type, whose size is always 1 in any standards-compliant C implementation. In addition, it is frequently very difficult to predict the sizes of compound datatypes such as a struct or union, due to structure "padding" (see Implementation below). Another reason for using sizeof is readability, since it avoids magic numbers.

Read more about this topic:  Sizeof