Struct (C programming language): Difference between revisions

From Wikipedia, the free encyclopedia
Jump to navigation Jump to search
imported>Aadirulez8
m v2.05 - Autofix / Fix errors for CW project (Link equal to linktext)
 
Declaration: Sorry for the very stupid reason earlier
 
Line 1: Line 1:
{{Short description|C keyword for defining a structured data type}}
{{Short description|C keyword for defining a structured data type}}
{{lowercase}}
{{lowercase}}
In the [[C programming language]], '''struct''' is the keyword used to define a [[composite data type|composite]], a.k.a. [[Record (computer science)|record]], [[data type]] {{endash}} a named set of values that occupy a block of memory. It allows for the different values to be accessed via a single [[identifier]], often a [[pointer (computer programming)|pointer]]. A struct can contain other data types so is used for mixed-data-type records. For example a bank customer struct might contains fields: name, address, telephone, balance.
In the [[C programming language]], '''struct''' is the keyword used to define a [[composite data type|composite]], a.k.a. [[Record (computer science)|record]], [[data type]] {{endash}} a named set of values that occupy a block of memory. It allows for the different values to be accessed via a single [[identifier]], often a [[pointer (computer programming)|pointer]]. 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 a ''contiguous block'' of memory, usually delimited (sized) by word-length boundaries. It corresponds to the similarly named feature available in some [[assembly language|assemblers]] for Intel processors. Being a block of contiguous memory, each field within a struct is located at a certain fixed offset from the start.
A struct occupies a ''contiguous block'' of memory, usually delimited (sized) by word-length boundaries. It corresponds to the similarly named feature available in some [[assembly language|assemblers]] for Intel processors. Being a block of contiguous memory, each field within a struct is located at a certain fixed offset from the start.
Line 10: Line 10:


== Declaration ==
== Declaration ==


The syntax for a struct declaration is shown by this simple example:
The syntax for a struct declaration is shown by this simple example:


<syntaxhighlight lang="C">
<syntaxhighlight lang="C">
struct tag_name {
struct TagName {
  type member1;
    Type member1;
  type member2;
    Type member2;
};
};
</syntaxhighlight>
</syntaxhighlight>


The <code>tag_name</code> is optional in some contexts.
The <code>TagName</code> is optional in some contexts.


==Typedef==
==Typedef==


Via the keyword [[Typedef|<code>typedef</code>]], a struct type can be referenced without using the <code>struct</code> keyword. However, some{{who|date=October 2021}} programming style guides advise against this, claiming that it can obfuscate the type.
Via the keyword [[Typedef|<code>typedef</code>]], a struct type can be referenced without using the <code>struct</code> keyword. However, some<ref>{{Cite web|url=https://www.kernel.org/doc/html/v4.10/process/coding-style.html#typedefs|title=Linux kernel coding style}}</ref> programming style guides advise against this, claiming that it can obfuscate the type.


For example:
For example:
<syntaxhighlight lang="C">
<syntaxhighlight lang="C">
typedef struct tag_name {
typedef struct TagName {
   type member1;
   Type member1;
   type member2;
   Type member2;
} thing_t;
} Thing;
thing_t thing;
 
// struct TagName can now be referred to as Thing
Thing thing;
</syntaxhighlight>
</syntaxhighlight>


In C++ code, typedef is not needed because types defined via <code>struct</code> are part of the regular namespace, so the type can be referred to as either <code>struct thing_t</code> or <code>thing_t</code>.
In C++ code, <code>typedef</code> is not needed because types defined via <code>struct</code> are part of the regular namespace, so the type can be referred to as either <code>struct Thing</code> or <code>Thing</code>. <code>typedef</code> in C++ is also superseded by the <code>using</code> statement, which can alias types that have [[template (C++)|templates]].


== Initialization ==
== Initialization ==
Line 44: Line 50:


<syntaxhighlight lang="c">
<syntaxhighlight lang="c">
struct point_t {
struct Point {
  int x;
    int x;
  int y;
    int y;
};
};
</syntaxhighlight>
</syntaxhighlight>
Line 53: Line 59:


<syntaxhighlight lang="c">
<syntaxhighlight lang="c">
struct point_t a = { 1, 2 };
struct Point a = { 1, 2 };
</syntaxhighlight>
</syntaxhighlight>


Line 59: Line 65:


<syntaxhighlight lang="c">
<syntaxhighlight lang="c">
struct point_t a = { .y = 2, .x = 1 };
struct Point a = { .y = 2, .x = 1 };
</syntaxhighlight>
</syntaxhighlight>


Line 67: Line 73:


<syntaxhighlight lang="c">
<syntaxhighlight lang="c">
struct point_t b = a;
struct Point b = a;
</syntaxhighlight>
</syntaxhighlight>


Line 75: Line 81:


<syntaxhighlight lang="c">
<syntaxhighlight lang="c">
struct point_t a = { 1, 3 };
struct Point a = { 1, 3 };
struct point_t b;
struct Point b;
b = a;
b = a;
</syntaxhighlight>
</syntaxhighlight>
Line 85: Line 91:


<syntaxhighlight lang="c">
<syntaxhighlight lang="c">
struct point_t point = { 3, 7 };
struct Point p = { 3, 7 };
int x = point.x;
int x = p.x;
point.x = 10;
p.x = 10;
struct point_t *pp = &point;
struct Point* pp = &p;
x = pp->x;
x = pp->x;
pp->x = 8;
pp->x = 8;
Line 94: Line 100:


== In other languages ==
== In other languages ==
[[D (programming language)|D]],<ref>{{cite web |title=Structs, Unions - D Programming Language |url=https://dlang.org/spec/struct.html |website=dlang.org |access-date=8 July 2025}}</ref> [[Go (programming language)|Go]], [[Julia (programming language)|Julia]],<ref>{{cite web |title=Types · The Julia Language |url=https://docs.julialang.org/en/v1/manual/types/#Composite-Types |website=docs.julialang.org |language=en}}</ref> [[Rust (programming language)|Rust]], [[Swift (programming language)|Swift]] and [[Zig (programming language)|Zig]]<ref>{{cite web |title=Structs {{!}} zig.guide |url=https://zig.guide/language-basics/structs/ |website=zig.guide |access-date=8 July 2025 |language=en |date=20 April 2024}}</ref> have structs.


===C++===
===C++===

Latest revision as of 10:58, 26 December 2025

Template:Short description Template:Lowercase In the C programming language, struct is the keyword used to define a composite, a.k.a. record, data type

  1. REDIRECT Template:En dash

Template:R protected a named set of values that occupy a block of memory. It allows for the different values to be accessed via a single identifier, often a pointer. 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 a contiguous block of memory, usually delimited (sized) by word-length boundaries. It corresponds to the similarly named feature available in some assemblers for Intel processors. Being a block of contiguous memory, each field within a struct is located at a certain fixed offset from the start.

The sizeof operator results in the number of bytes needed to store a particular struct, just as it does for a primitive data type. The alignment of particular fields in the struct (with respect to word 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 in ALGOL 68.[2]

Declaration

The syntax for a struct declaration is shown by this simple example:

struct TagName {
    Type member1;
    Type member2;
};

The TagName is optional in some contexts.

Typedef

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

For example:

typedef struct TagName {
   Type member1;
   Type member2;
} Thing;

// struct TagName can now be referred to as Thing
Thing thing;

In C++ code, typedef is not needed because types defined via struct are part of the regular namespace, so the type can be referred to as either struct Thing or Thing. typedef in C++ is also superseded by the using statement, which can alias types that have templates.

Initialization

There are three ways to initialize a structure.

For the type:

struct Point {
    int x;
    int y;
};

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

struct Point a = { 1, 2 };

For non contiguous or out of order members list, designated initializer style may be used.[5] For example:

struct Point a = { .y = 2, .x = 1 };

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. For example:

struct Point b = a;

Copy

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

struct Point a = { 1, 3 };
struct Point b;
b = a;

Pointers

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

struct Point p = { 3, 7 };
int x = p.x;
p.x = 10;
struct Point* pp = &p;
x = pp->x;
pp->x = 8;

In other languages

D,[6] Go, Julia,[7] Rust, Swift and Zig[8] have structs.

C++

In C++, struct is essentially the same as for C. Further, a class is the same as a struct but with different default visibility: class members are private by default, whereas struct members are public by default.

.NET

.NET languages have a feature similar to struct in C

  1. REDIRECT Template:En dash

Template:R protected called struct in C# and Structure in Visual Basic .NET). This construct provides many features of a class, but acts as a value type instead of a reference 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.[9]

See also

References

<templatestyles src="Reflist/styles.css" />

  1. Script error: No such module "citation/CS1".
  2. Script error: No such module "Citation/CS1".
  3. Script error: No such module "citation/CS1".
  4. Script error: No such module "citation/CS1".
  5. Script error: No such module "citation/CS1".
  6. Script error: No such module "citation/CS1".
  7. Script error: No such module "citation/CS1".
  8. Script error: No such module "citation/CS1".
  9. Script error: No such module "citation/CS1".

Script error: No such module "Check for unknown parameters".