Sizeof

Sizeof

In the programming languages C and C++, the unary operator 'sizeof' is used to calculate the sizes of datatypes. sizeof can be applied to all datatypes, be they primitive types such as the integer and floating-point types defined in the language, pointers to memory addresses, or the compound datatypes (unions, structs, or C++ classes) defined by the programmer. sizeof is a compile-time operator that returns the size, in multiples of the size of char, of the variable or parenthesized type-specifier that it precedes. The size of char on most architectures is 1 byte (usually 8 bits) so for all practical purposes sizeof effectively returns the size in bytes

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, (s)he doesn't know how many bytes to ask malloc for. Therefore, it is necessary to use the operator sizeof:

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

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 a single object of type int takes up, multiplied by 10, ensuring enough space for all 10 ints.

It is generally not safe for a programmer to assume he or she knows 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, it is recommended by many programmers to always use sizeof, as the size of an int could change when code is ported to a different system, breaking the code. 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, as this avoids magic numbers.

Use

The 'sizeof' operator is used to determine the amount of space any data-element/datatype occupies in memory. To use sizeof, the keyword "sizeof" is followed by a type name, variable, or expression. If a type name is used, it always needs to be enclosed in parentheses, whereas variable names and expressions can be specified with or without parentheses. A sizeof expression evaluates to an unsigned value equal to the size in bytes of the "argument" datatype, variable, or expression (with datatypes, sizeof evaluates to the size of the datatype; for variables and expressions it evaluates to the size of the type of the variable or expression). For example, assuming ints are 4 bytes long, the following code will print 1,4:

/* the following code illustrates the use of sizeof * with variables and expressions (no parentheses needed), * and with type names (parentheses needed) */

char c;

printf("%u,%u", (unsigned) sizeof c, (unsigned) sizeof(int) );

The value of a sizeof expression is always non-negative as the C standard specifies that the type of such an expression is size_t, defined to be an unsigned integer type.

Using sizeof with arrays

When sizeof is applied to an array, the result is the size in bytes of the array in memory. The following program uses sizeof to determine the size of an array, avoiding a buffer overflow when copying characters:

/*the following program demonstrates sizeof applied to arrays*/

#include
#include

int main(int argc, char *argv [] ){ char buffer [10] ; /*array of 10 char*/ /*only copy 9 characters from argv [1] into buffer (sizeof(char) *is defined to be 1, so the number of elements in buffer *is equal to its size in bytes) */ strncpy(buffer, argv [1] , sizeof(buffer) - 1); /*set the last element of the buffer equal to the null character*/ buffer [sizeof(buffer) - 1] = '


Wikimedia Foundation. 2010.

Игры ⚽ Нужно решить контрольную?

Look at other dictionaries:

  • Comparison of Object Pascal and C — Programming language comparisons General comparison Basic syntax Basic instructions Arrays Associative arrays String operations …   Wikipedia

  • Pointer (computing) — This article is about the programming data type. For the input interface (for example a computer mouse), see Pointing device. Pointer a pointing to the memory address associated with variable b. Note that in this particular diagram, the computing …   Wikipedia

  • Compatibility of C and C++ — Programming language comparisons General comparison Basic syntax Basic instructions Arrays Associative arrays String operations …   Wikipedia

  • C (programming language) — C The C Programming Language[1] (aka K R ) is the seminal book on C …   Wikipedia

  • Operators in C and C++ — This is a list of operators in the C and C++ programming languages. All the operators listed exist in C++; the fourth column Included in C , dictates whether an operator is also present in C. Note that C does not support operator overloading.… …   Wikipedia

  • C++ — Desarrollador(es) Bjarne Stroustrup, Bell Labs Información general …   Wikipedia Español

  • Operadores de C y C++ — Esta es una lista de los grandes operadores de los lenguajes de programación C y C++. Todos los operadores listados existen en C++. La tercera columna indica si también están presentes en C. También hay que tener en cuenta que C no permite la… …   Wikipedia Español

  • Сокеты Беркли — Сокеты Беркли  интерфейс программирования приложений (API), представляющий собой библиотеку для разработки приложений на языке Си с поддержкой межпроцессного взаимодействия (IPC), часто применяемый в компьютерных сетях. Сокеты Беркли (также… …   Википедия

  • Berkeley sockets — The Berkeley sockets application programming interface (API) comprises a library for developing applications in the C programming language that perform inter process communication, most commonly across a computer network.Berkeley sockets (also… …   Wikipedia

  • Function object — A function object, also called a functor or functional, is a computer programming construct allowing an object to be invoked or called as if it were an ordinary function, usually with the same syntax.Function objects are unrelated to functors in… …   Wikipedia

Share the article and excerpts

Direct link
Do a right-click on the link above
and select “Copy Link”