Struct (C programming language)In the C programming language, struct is the keyword used to define a composite, 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 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 contains fields: name, address, telephone, 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 The C struct feature was derived from the same-named concept in ALGOL 68.[2] DeclarationThe syntax for a struct declaration is shown by this simple example: struct tag_name {
type member1;
type member2;
};
The TypedefVia the keyword For example: typedef struct tag_name {
type member1;
type member2;
} thing_t;
thing_t thing;
In C++ code, typedef is not needed because types defined via InitializationThere are three ways to initialize a structure. For the type: struct point_t {
int x;
int y;
};
C89-style initializers are used when contiguous members may be given.[3] For example: struct point_t a = { 1, 2 };
For non contiguous or out of order members list, designated initializer style may be used.[4] For example: struct point_t 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_t b = a;
CopyThe state of a struct can be copied to another instance. A compiler might use struct point_t a = { 1, 3 };
struct point_t b;
b = a;
PointersPointers can be used to refer to a struct point_t point = { 3, 7 };
int x = point.x;
point.x = 10;
struct point_t *pp = &point;
x = pp->x;
pp->x = 8;
In other languagesC++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 – called See also
References
|
Portal di Ensiklopedia Dunia