Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikipediaThe Free Encyclopedia
Search

struct (C programming language)

From Wikipedia, the free encyclopedia
C keyword for defining a structured data type

In theC programming language,struct (referring to astructure) is thekeyword used to define acomposite, a.k.a.record,data type – a named set of values that occupy a block of memory. It allows for the different values to be accessed via a singleidentifier, often apointer. A struct can contain other data types so is used for mixed-data-type records. For example, a bank customer struct might contain fields for the customer's name, address, telephone number, and balance.

A struct occupies acontiguous block of memory, usually delimited (sized) by word-length boundaries.[clarification needed] It corresponds to the similarly named feature available in someassemblers for Intel processors. Being a block of contiguous memory, each field within a struct is located at a certain fixed offset from the start.

Thesizeof operator results in the number of bytes needed to store a particular struct, just as it does for aprimitive data type. The alignment of particular fields in the struct (with respect toword boundaries) is implementation-specific and may include padding. Modern compilers typically support the#pragma pack directive, which sets the size in bytes for alignment.[1]

The C struct feature was derived from the same-named concept inALGOL 68.[2]

Declaration

[edit]

The following simple example depicts declaring a struct namedMyStruct, with two fields of typesType1 andType2 respectively.

structMyStruct{Type1member1;Type2member2;};

The added nameMyStruct is optional in some contexts.

Members may possibly be padded formemory alignment, and thus it is often recommended to order fields from largest to smallest size for efficient memory usage.

A function may directly return a struct, although this is often not efficient at run-time. SinceC99, a struct may also end with aflexible array member.

Structs can be composed of other structs:

structDate{intyear;intmonth;intday;};structBirthday{charname[50];structDatedob;};

It is legal to declare an anonymous struct within a struct, but it cannot be named in C (as there is no notion of nested types, unlike C++ where nesting named structs is legal).

structPerson{charname[50];intage;struct{charcity[50];intzip;}addr;};

A struct containing a pointer to a struct of its own type is commonly used to buildlinked data structures:

structLinkedList{void*item;// stores the current itemstructLinkedList*next;// stores the next list, or NULL if nothing next};

Circularly referencing between two structs must be done using aforward declaration and pointers:

structB;structA{structB*b;};structB{structA*a;};

Typedef

[edit]
Main article:Typedef

Via the keywordtypedef, a struct type can be referenced without using thestruct keyword. However, some[3] programming style guides advise against this, claiming that it can obfuscate the type.

For example:

typedefstructMyStruct{Type1member1;Type2member2;}Thing;// struct MyStruct can now be referred to as 'Thing'Thingthing;

In C++ code, the type may be referred to as eitherstruct Thing orThing (without any need fortypedef).typedef in C++ is also superseded by theusing statement, which can alias types that havetemplates.

Initialization

[edit]

Considering the struct declaration:

structPoint{intx;inty;};

There are three ways to initialize a structure:

C89-style initializers are used when contiguous members may be given.[4] For example:

structPointa={1,2};

For non contiguous or out of order members list, thedesignated initializer style (introduced in C99) may be used.[5] For example:

structPointa={.x=1,.b=2};// May initialize fields out of order toostructPointb={.y=4,.x=-3};

If an initializer is given or if the object isstatically 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. For example:

structPointb=a;

Copy

[edit]

The state of a struct can be copied to another instance. A compiler might usememcpy() to copy the bytes of the memory block.

structPointa={1,3};structPointb;b=a;

Bit fields

[edit]
Main article:Bit field

Structs may also use bit fields to allow fields to share the same storage units, but layouts are implementation-defined.

structProperties{// three fields can be compactly packed in one byteunsignedcharvisible:1;// a occupies 1 bitunsignedcharcolor:3;// b occupies 3 bitsunsignedcharsize:4;// c occupies 4 bits};

Pointers

[edit]

Pointers can be used to refer to astruct by its address. This is useful for passing a struct to a function to avoid the overhead of copying the struct. The-> operatordereferences the pointer (left operand) and accesses the value of a struct member (right operand).

structPointp={3,7};intx=p.x;p.x=10;structPoint*pp=&p;x=pp->x;pp->x=8;

Functions may take a struct as a parameter by value, but this is expensive as it copies the entire struct. Meanwhile, passing it by pointer is often preferable as the size of a pointer is known (typically 4 or 8 bytes).

#include<stdio.h>// a larger struct which may carry a lot of datastructStudent{charname[50];unsignedintid;unsignedintsemester;floatgpa;};// passing by valuevoidprint_student(structStudents){printf("Name: %s, ID: %d, in semester %d, with GPA: %.2f\n",s.name,s.id,s.semester,s.gpa);}// passing by pointervoidprint_student(structStudent*s){printf("Name: %s, ID: %d, in semester %d, with GPA: %.2f\n",s->name,s->id,s->semester,s->gpa);}

In other languages

[edit]

Crystal (programming language),[6]D,[7]Go,Julia,[8]Rust,Swift andZig[9] have structs.

C++

[edit]

InC++, struct is essentially the same as for C, but also with methods. Further, aclass is the same as a struct but with different defaultvisibility: class members are private by default, whereas struct members are public by default.

.NET

[edit]

.NET languages have a feature similar to struct in C – calledstruct inC# andStructure inVisual Basic .NET). This construct provides many features of a class, but acts as avalue type instead of areference type. For example, when passing a .NET struct to a function, the value is copied so that changes to the input parameter do not affect the value passed in.[10]

See also

[edit]

References

[edit]
  1. ^"Struct memory layout in C".Stack Overflow.
  2. ^Ritchie, Dennis M. (March 1993)."The Development of the C Language".ACM SIGPLAN Notices.28 (3):201–208.doi:10.1145/155360.155580.The scheme of type composition adopted by C owes considerable debt to Algol 68, although it did not, perhaps, emerge in a form that Algol's adherents would approve of. The central notion I captured from Algol was a type structure based on atomic types (including structures), composed into arrays, pointers (references), and functions (procedures). Algol 68's concept of unions and casts also had an influence that appeared later.
  3. ^"Linux kernel coding style".
  4. ^Kelley, Al; Pohl, Ira (2004).A Book On C: Programming in C (Fourth ed.). pp. 418.ISBN 0-201-18399-4.
  5. ^"IBM Linux compilers. Initialization of structures and unions".
  6. ^"Structs - Crystal".crystal-lang.org. Retrieved8 February 2026.
  7. ^"Structs, Unions - D Programming Language".dlang.org. Retrieved8 July 2025.
  8. ^"Types · The Julia Language".docs.julialang.org.
  9. ^"Structs | zig.guide".zig.guide. 20 April 2024. Retrieved8 July 2025.
  10. ^"Parameter passing in C#".
Retrieved from "https://en.wikipedia.org/w/index.php?title=Struct_(C_programming_language)&oldid=1337321753"
Category:
Hidden categories:

[8]ページ先頭

©2009-2026 Movatter.jp