Share to: share facebook share twitter share wa share telegram print page

Struct (C programming language)

A struct in the C programming language (and many derivatives) is a composite data type (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 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 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 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.[1]

In the C++ language, a struct is identical to a C++ class 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 struct data type.[2]

Like its C counterpart, the struct data type in C# (Structure in Visual Basic .NET) is similar to a class. 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).[3]

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++, the only difference between a struct and a class is that the members and base classes of a struct are public by default. (A class defined with the class keyword has private members and base classes by default.)

Declaration

The general syntax for a struct declaration in C is:

struct tag_name {
   type member1;
   type member2;
   /* declare as many members as desired, but the entire structure size must be known to the compiler. */
};

Here tag_name is optional in some contexts.

Such a struct declaration may also appear in the context of a typedef declaration of a type alias or the declaration or definition of a variable:

typedef struct tag_name {
   type member1;
   type member2;
} 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 {
   int x;
   int y;
};

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

/* Define variable 'a' of type point, and initialize its first two members in place */
struct point a = { 1, 2 };

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

/* Define variable 'a' of type point, and set members using designated initializers */
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

/* Define variable 'b' of type point, and set members to the same values as those of 'a' */
struct point b = a;

Assignment

A struct may be assigned to another struct. A compiler might use memcpy() to perform such an assignment.

struct point {
    int x;
    int y;
};

int main(void)
{
    struct point a = { 1, 3 }; /* initialized variable */
    struct point b;            /* uninitialized */
    b = a;                     /* copy member values from 'a' into 'b' */
    return 0;
}

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 {
   int x;
   int y;
};
struct point my_point = { 3, 7 };
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

References

  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. ^ "Parameter passing in C#".
  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".

Read other articles:

Губернатор Ханты-Мансийского автономного округа - Югры Должность занимает Комарова, Наталья Владимировна с 1 марта 2010 года Должность Возглавляет Ханты-Мансийский автономный округ — Югра Кандидатура Президентом России Назначается Думой ХМАО Срок полномочий 5 лет Появила…

I'm Not the Only One AuthorGeorge GallowayCountryUnited KingdomLanguageEnglishSubjectBritish politicsPublishedLondonPublisherAllen LanePublication date2004Media typePrintISBN0713998075Dewey Decimal320.914 I'm Not the Only One is a 2004 political autobiography by the British politician George Galloway. The book details his political beginnings in the Labour Party in Glasgow, his opposition to the invasion of Iraq, support for the Palestinian cause and the founding of the Respect Party.[1…

Pokonyan!ポコニャン! MangaPengarangFujiko F. FujioPenerbitUshio Publishing Co.,Ltd.ImprintKibō ComicsMajalahKibō no TomoDemografiKodomoTerbitApril 1975 – Mei 1978Volume2 Seri animeSutradaraHiroshi Sasagawa (Sutradara kepala)Seitarō HaraSkenarioShun'ichi YukimuroMusikMasae SagaraKeita MiyaharaStudioAnimation 21PelisensiEnoki Films USASaluranasliNHK General TV (episode 1-150)NHK Educational TV (episode 151-170)Tayang 5 April 1993 – 30 Maret 1996Episode170  Portal anime dan man…

Truck bombing in Chechnya 43°40′34″N 45°07′37″E / 43.676°N 45.127°E / 43.676; 45.127 2003 Znamenskoye suicide bombingPart of the Second Chechen WarLocation of Chechnya in RussiaLocationZnamenskoye, Nadterechny District, Chechnya, RussiaDate12 May 2003Attack typeSuicide attackDeaths59Injured200 vteSecond Chechen War(guerrilla phase) Insurgency since May 2000 Galashki 1st suicide bombings 2nd suicide bombings Alkhan-Kala Vedeno 1st Grozny crash Tsotsin-Yurt Shel…

Ulrich von Brockdorff-RantzauForeign Minister of GermanyIn office13 December 1918 – 20 June 1919PresidentFriedrich EbertChancellorPhilipp Scheidemann (Ministerpräsident)Preceded byWilhelm Solf (Imperial Germany) Council of the People's DeputiesSucceeded byHermann MüllerGerman Ambassador to the Soviet UnionIn officeNovember 1922 – 8 September 1928Preceded byKurt WiedenfeldSucceeded byHerbert von Dirksen Personal detailsBorn(1869-05-29)29 May 1869Schleswig, Kingdom of Pruss…

Pemandangan kota Vitória Vitória merupakan sebuah kota di Brasil. Kota ini letaknya di bagian tenggara. Tepatnya di negara bagian Espirito Santo. Pada tahun 2005, kota ini memiliki jumlah penduduk sebanyak 313.312 jiwa dan memiliki luas wilayah 93 km². Kota ini memiliki angka kepadatan penduduk sebesar 3.360 jiwa/km². Di wilayah metropolitan, berjumlah 1.627.651 jiwa. Kota kembar Vitoria-Gasteiz, Spanyol Oita, Jepang Havana, Kuba Mantova, Italia Darmstadt, Jerman Vila Velha, Brasil Casc…

كيمياء كهربائيةصنف فرعي من كيمياء فيزيائية جزء من كيمياء فيزيائية يمتهنه electrochemist (en) التاريخ history of electrochemistry (en) تعديل - تعديل مصدري - تعديل ويكي بيانات خلية كهروكيميائية وتتكون من لوحين معدنيين مختلفين في كهرل ، وقد أضيف إليهما لوح ثالث (في الوسط) كلوح مرجعي لإجراء قياسات. الك

ماري من برابانت، إمبراطورة رومانية مقدسة إمبراطورة رومانية مقدسةملكة ألمانيا فترة الحكم19 مايو 1214 - 5 يوليو 1215 كونتيسة هولندا فترة الحكميوليو 1220 - 4 فبراير 1222 معلومات شخصية الميلاد سنة 1190[1]  لُوفِن  الوفاة 14 يونيو 1260 (69–70 سنة)[1]  لُوفِن  مكان الدفن كنيسة سان…

President of Venezuela from 1952 to 1958 For other people named Marcos Pérez, see Marcos Pérez (disambiguation). In this Spanish name, the first or paternal surname is Pérez and the second or maternal family name is Jiménez. This article needs additional citations for verification. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.Find sources: Marcos Pérez Jiménez – news · newspapers…

Аджамська сільська громадаОсновні даніКраїна  УкраїнаОбласть Кіровоградська областьРайон Кропивницький районКод КАТОТТГ UA35040010000022631Утворена 12 червня 2020 рокуАдмін. центр АджамкаТериторія та населенняПлоща 291,76 км²Населення 6088 осіб (2019)Густота 20,87 осіб/км²Населені пун…

فاغوتينيمعلومات عامةالمنشأ إيطاليا النوع معكرونة تعديل - تعديل مصدري - تعديل ويكي بياناتفاغوتيني (الإيطالية: Fagottini، وتعني حرفياً: حُزم صغيرة) وهي نوع من المعكرونة الإيطالية. وتكون ذات شكل عادي تقليدي محشو بالخضروات المطبخوة بالبخار، مثل الجزر والفاصوليا الخضراء مع

أنو كومي تقسيم إداري البلد اليونان  [1] خصائص جغرافية إحداثيات 40°13′38″N 21°49′46″E / 40.22719167°N 21.82942778°E / 40.22719167; 21.82942778  الارتفاع 445 متر  السكان التعداد السكاني 1436 (إحصاء السكان) (2011)  معلومات أخرى التوقيت ت ع م+02:00 (توقيت قياسي)،  وت ع م+03:00 (توقيت صيفي)  50…

This article needs additional citations for verification. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.Find sources: Theatre of Vietnam – news · newspapers · books · scholar · JSTOR (February 2022) (Learn how and when to remove this template message) 1920s Tuồng theatre actors Theatre of Vietnam comprises many traditional forms of drama which survive and retain their popularit…

Armenian environmentalist Hakob SanasaryanHakob Sanasaryan during a field trip, 2011Born (1936-12-21) 21 December 1936 (age 86)Yeranos, ArmeniaNationalityArmenianKnown forGrassroots Environmentalism in Former Soviet UnionFounder of Environmental Movement in ArmeniaPresident of the Greens Union of ArmeniaOfficeMember of the Supreme Council (Armenia) (First Convocation, 1990-1995) and Deputy Chairman of the Parliamentarian Committee on Nature Protection and Natural Resources.Alma ma…

2022 conflict between the Belarusian government and pro-Ukrainian activists You can help expand this article with text translated from the corresponding article in Russian. (April 2022) Click [show] for important translation instructions. View a machine-translated version of the Russian article. Machine translation, like DeepL or Google Translate, is a useful starting point for translations, but translators must revise errors as necessary and confirm that the translation is accurate, rather…

2016 video game 2016 video gameFinal Fantasy XVDeveloper(s)Square Enix Business Division 2Publisher(s)Square EnixDirector(s)Hajime TabataProducer(s)Shinji HashimotoDesigner(s)Takatsugu NakazawaArtist(s)Tetsuya NomuraRoberto FerrariYusuke NaoraIsamu KamikokuryoWriter(s)Saori ItamuroAkiko IshibashiTakumi NishidaComposer(s)Yoko ShimomuraSeriesFinal FantasyEngineLuminous EnginePlatform(s)PlayStation 4Xbox OneWindowsGoogle StadiaReleasePlayStation 4, Xbox OneNovember 29, 2016WindowsMarch 6, 2018Googl…

1751 poem by Thomas Gray First page of Dodsley's illustrated edition of Gray's Elegy with illustration by Richard Bentley Elegy Written in a Country Churchyard is a poem by Thomas Gray, completed in 1750 and first published in 1751.[1] The poem's origins are unknown, but it was partly inspired by Gray's thoughts following the death of the poet Richard West in 1742. Originally titled Stanzas Wrote in a Country Church-Yard, the poem was completed when Gray was living near the Church of St …

Genus of snakes Leptodeira Northern cat-eyed snake (Leptodeira septentrionalis), in Osa Peninsula, Costa Rica Scientific classification Domain: Eukaryota Kingdom: Animalia Phylum: Chordata Class: Reptilia Order: Squamata Suborder: Serpentes Family: Colubridae Subfamily: Dipsadinae Genus: LeptodeiraFitzinger, 1843 Species 18, see text Synonyms Megalops Hallowell 1860 [1861] Leptodira Cope 1866 Anoplophallus Cope 1893 Leptodeira is a genus of colubrid snakes commonly referred to as cat-eyed snakes…

Australian Paralympic tennis player David Johnson2000 Australian Paralympic team portrait of JohnsonPersonal informationNationality AustraliaBorn (1969-09-16) 16 September 1969 (age 54)Beaudesert, Queensland Medal record Wheelchair tennis Representing  Australia Paralympic Games 2000 Sydney Men's Doubles Johnson takes a backhand swing at the ball during 2000 Summer Paralympics match David Johnson (born 16 September 1969) is an Australian Paralympic tennis player. He won a silver m…

Thiede Stadt Salzgitter Ortswappen von Salzgitter-Thiede Koordinaten: 52° 11′ N, 10° 29′ O52.18722222222210.48388888888989Koordinaten: 52° 11′ 14″ N, 10° 29′ 2″ O Höhe: 89 (82–105) m Fläche: 12,26 km² Einwohner: 10.888 (31. Dez. 2022) Bevölkerungsdichte: 888 Einwohner/km² Eingemeindung: 1. April 1942 Postleitzahl: 38239 Vorwahl: 05341 Karte Lage von Thiede in Salzgitter Thiede ist einer der ins…

Kembali kehalaman sebelumnya

Lokasi Pengunjung: 3.14.143.212