Struct (C programming language)
   HOME

TheInfoList



OR:

A struct in the
C programming language ''The C Programming Language'' (sometimes termed ''K&R'', after its authors' initials) is a computer programming book written by Brian Kernighan and Dennis Ritchie, the latter of whom originally designed and implemented the language, as well as ...
(and many derivatives) is a
composite data type In computer science, a composite data type or compound data type is any data type which can be constructed in a program using the programming language's primitive data types and other composite types. It is sometimes called a structure or aggreg ...
(or record) declaration that defines a physically grouped list of variables under one name in a block of memory, allowing the different variables to be accessed via a single pointer or by the struct declared name which returns the same address. The struct data type can contain other data types so is used for mixed-data-type records such as a hard-drive directory entry (file length, name, extension, physical address, etc.), or other mixed-type records (name, address, telephone, balance, etc.). The C struct directly references a ''contiguous block'' of physical memory, usually delimited (sized) by word-length boundaries. It corresponds to the similarly named feature available in some
assemblers Assembler may refer to: Arts and media * Nobukazu Takemura, avant-garde electronic musician, stage name Assembler * Assemblers, a fictional race in the ''Star Wars'' universe * Assemblers, an alternative name of the superhero group Champions of A ...
for Intel processors. Being a block of contiguous memory, each field within a struct is located at a certain fixed offset from the start. Because the contents of a struct are stored in contiguous memory, the
sizeof sizeof is a unary operator in the programming languages C and C++. It generates the storage size of an expression or a data type, measured in the number of ''char''-sized units. Consequently, the construct ''sizeof (char)'' is guaranteed to be ' ...
operator must be used to get the number of bytes needed to store a particular type of struct, just as it can be used for primitives. The alignment of particular fields in the struct (with respect to
word A word is a basic element of language that carries an semantics, objective or pragmatics, practical semantics, meaning, can be used on its own, and is uninterruptible. Despite the fact that language speakers often have an intuitive grasp of w ...
boundaries) is implementation-specific and may include padding, although modern compilers typically support the #pragma pack directive, which changes the size in bytes used for alignment. In the
C++ C++ (pronounced "C plus plus") is a high-level general-purpose programming language created by Danish computer scientist Bjarne Stroustrup as an extension of the C programming language, or "C with Classes". The language has expanded significan ...
language, a struct is identical to a
C++ class C class may refer to: Ships * C-class destroyer (disambiguation), multiple destroyers * C-class submarine (disambiguation), multiple submarines * C-class corvette (disambiguation), ships of the Victorian Royal Navy * C-class cruiser, Royal Navy ...
but has a different default visibility: class members are private by default, whereas struct members are public by default.


In other languages

The struct data type in C was derived from the
ALGOL 68 ALGOL 68 (short for ''Algorithmic Language 1968'') is an imperative programming language that was conceived as a successor to the ALGOL 60 programming language, designed with the goal of a much wider scope of application and more rigorously de ...
struct data type. Like its C counterpart, the struct data type in C# (''Structure'' in
Visual Basic .NET Visual Basic, originally called Visual Basic .NET (VB.NET), is a multi-paradigm, object-oriented programming language, implemented on .NET, Mono, and the .NET Framework. Microsoft launched VB.NET in 2002 as the successor to its original Visua ...
) is similar to a
class Class or The Class may refer to: Common uses not otherwise categorized * Class (biology), a taxonomic rank * Class (knowledge representation), a collection of individuals or objects * Class (philosophy), an analytical concept used differentl ...
. The biggest difference between a struct and a class in these languages is that when a struct is passed as an argument to a function, any modifications to the struct in that function will not be reflected in the original variable (unless pass-by-reference is used). This differs from C++, where classes or structs can be statically allocated or dynamically allocated either on the stack (similar to C#) or on the heap, with an explicit pointer. In
C++ C++ (pronounced "C plus plus") is a high-level general-purpose programming language created by Danish computer scientist Bjarne Stroustrup as an extension of the C programming language, or "C with Classes". The language has expanded significan ...
, the only difference between a struct and a
class Class or The Class may refer to: Common uses not otherwise categorized * Class (biology), a taxonomic rank * Class (knowledge representation), a collection of individuals or objects * Class (philosophy), an analytical concept used differentl ...
is that the members and base classes of a struct are
public In public relations and communication science, publics are groups of individual people, and the public (a.k.a. the general public) is the totality of such groupings. This is a different concept to the sociological concept of the ''Öffentlichkei ...
by default. (A class defined with the class keyword has
private Private or privates may refer to: Music * " In Private", by Dusty Springfield from the 1990 album ''Reputation'' * Private (band), a Denmark-based band * "Private" (Ryōko Hirosue song), from the 1999 album ''Private'', written and also recorde ...
members and base classes by default.)


Declaration

The general syntax for a struct declaration in C is: struct tag_name ; Here tag_name is optional in some contexts. Such a struct declaration may also appear in the context of a
typedef typedef is a reserved keyword in the programming languages C, C++, and Objective-C. It is used to create an additional name (''alias'') for another data type, but does not create a new type, except in the obscure case of a qualified typedef of ...
declaration of a type alias or the declaration or definition of a variable: typedef struct tag_name struct_alias;


Initialization

There are three ways to initialize a structure. For the struct type /* Declare the struct with integer members x, y */ struct point ; ''C89-style initializers'' are used when contiguous members may be given. /* Define a variable p of type point, and initialize its first two members in place */ struct point p = ; For non contiguous or out of order members list, ''designated initializer'' style may be used /* Define a variable p of type point, and set members using designated initializers */ struct point p = ; If an initializer is given or if the object is statically allocated, omitted elements are initialized to 0. A third way of initializing a structure is to copy the value of an existing object of the same type /* Define a variable q of type point, and set members to the same values as those of p */ struct point q = p;


Assignment

A struct may be assigned to another struct. A compiler might use memcpy() to perform such an assignment. struct point ; int main(void)


Pointers to struct

Pointers can be used to refer to a struct by its address. This is useful for passing structs to a function. The pointer can be dereferenced using the * operator. The -> operator dereferences the pointer to struct (left operand) and then accesses the value of a member of the struct (right operand). struct point ; struct point my_point = ; struct point *p = &my_point; /* p is a pointer to my_point */ (*p).x = 8; /* set the first member of the struct */ p->x = 8; /* equivalent method to set the first member of the struct */


See also

*
Bit field A bit field is a data structure that consists of one or more adjacent bits which have been allocated for specific purposes, so that any single bit or group of bits within the structure can be set or inspected. A bit field is most commonly used to ...
*
Flexible array member C struct data types may end with a flexible array member with no specified size: struct vectord ; Typically, such structures serve as the header in a larger, variable memory allocation: struct vectord *vector = malloc(...); vector->len ...
*
Passive data structure In computer science and object-oriented programming, a passive data structure (PDS, also termed a plain old data structure, or plain old data, POD) is a term for a record, to contrast with objects. It is a data structure that is represented only ...
*
Union type In computer science, a union is a value that may have any of several representations or formats within the same position in memory; that consists of a variable that may hold such a data structure. Some programming languages support special data ...


References

{{lowercase C (programming language)