Contents 1 In other languages 2 Declaration 3 Struct initialization 4 Assignment 5 Pointers to struct 6 typedef 7 See also 8 References

In other languages[edit] 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[edit] 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; Often, such entities are better declared separately, as in: typedef struct tag_name struct_alias; // These two statements now have the same meaning: // struct tag_name struct_instance; // struct_alias struct_instance; For example: struct account { int account_number; char *first_name; char *last_name; float balance; }; defines a type, referred to as struct account. To create a new variable of this type, we can write struct account s; which has an integer component, accessed by s.account_number, and a floating-point component, accessed by s.balance, as well as the first_name and last_name components. The structure s contains all four values, and all four fields may be changed independently. A pointer to an instance of the "account" structure will point to the memory address of the first variable, "account_number". The total storage required for a struct object is the sum of the storage requirements of all the fields, plus any internal padding.

Struct initialization[edit] There are three ways to initialize a structure. For the struct type /* Forward declare a type "point" to be a struct. */ typedef struct point point; /* 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 a variable p of type point, and initialize its first two members in place */ point p = { 1, 2 }; For non contiguous or out of order members list, designated initializer style[5] may be used /* Define a variable p of type point, and set members using designated initializers*/ point p = { .y = 2, .x = 1 }; If an initializer is given or if the object is statically allocated, omitted elements are initialized to 0.[6] 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 */ point q = p;

Assignment[edit] The following assignment of a struct to another struct will copy as one might expect. Depending on the contents, a compiler might use memcpy() in order to perform this operation. #include <stdio.h> /* Define a type point to be a struct with integer members x, y */ typedef struct { int x; int y; } point; int main(void) { /* Define a variable p of type point, and initialize all its members inline! */ point p = { 1, 3 }; /* Define a variable q of type point. Members are uninitialized. */ point q; /* Assign the value of p to q, copies the member values from p into q. */ q = p; /* Change the member x of q to have the value of 3 */ q.x = 3; /* Demonstrate we have a copy and that they are now different. */ if (p.x != q.x) printf("The members are not equal! %d != %d", p.x, q.x); /* Define a variable r of type point. Members are uninitialized. */ point r; /* Assign values using compound literal (ISO C99/supported by GCC > 2.95) */ r = (point) { 1, 2 }; return 0; }

Pointers to struct[edit] Pointers can be used to refer to a struct by its address. This is particularly useful for passing structs to a function by reference or to refer to another instance of the struct type as a field. The pointer can be dereferenced just like any other pointer in C, using the * operator. There is also a -> operator in C which 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; /* To declare and define p as a pointer of type struct point, and initialize it with the address of my_point. */ (*p).x = 8; /* To access the first member of the struct */ p->x = 8; /* Another way to access the first member of the struct */ C does not allow recursive declaration of struct; a struct can not contain a field that has the type of the struct itself. But pointers can be used to refer to an instance of it: typedef struct list_element list_element; struct list_element { point p; list_element * next; }; list_element el = { .p = { .x = 3, .y =7 }, }; list_element le = { .p = { .x = 4, .y =5 }, .next = &el }; Here the instance el would contain a point with coordinates 3 and 7. Its next pointer would be a null pointer since the initializer for that field is omitted. The instance le in turn would have its own point and its next pointer would refer to el.

typedef[edit] Main article: typedef Typedefs can be used as shortcuts, for example: typedef struct { int account_number; char *first_name; char *last_name; float balance; } account; Different users have differing preferences; proponents usually claim: shorter to write can simplify more complex type definitions can be used to forward declare a struct type As an example, consider a type that defines a pointer to a function that accepts pointers to struct types and returns a pointer to struct: Without typedef: struct point { int x; int y; }; struct point *(*point_compare_func) (struct point *a, struct point *b); With typedef: typedef struct point point_type; struct point { int x; int y; }; point_type *(*point_compare_func) (point_type *a, point_type *b); A common naming convention for such a typedef is to append a "_t" (here point_t) to the struct tag name, but such names are reserved by POSIX so such a practice should be avoided. A much easier convention is to use just the same identifier for the tag name and the type name: typedef struct point point; struct point { int x; int y; }; point *(*point_compare_func) (point *a, point *b); Without typedef a function that takes function pointer the following code would have to be used. Although valid, it becomes increasingly hard to read. /* Using the struct point type from before */ /* Define a function that returns a pointer to the biggest point, using a function to do the comparison. */ struct point * biggest_point (size_t size, struct point *points, struct point *(*point_compare) (struct point *a, struct point *b)) { int i; struct point *biggest = NULL; for (i=0; i < size; i++) { biggest = point_compare(biggest, points + i); } return biggest; } Here a second typedef for a function pointer type can be useful typedef point *(*point_compare_func_type) (point *a, point *b); Now with the two typedefs being used the complexity of the function signature is drastically reduced. /* Using the struct point type from before and the typedef for the function pointer */ /* Define a function that returns a pointer to the biggest point, using a function to do the comparison. */ point * biggest_point (size_t size, point * points, point_compare_func_type point_compare) { int i; point * biggest = NULL; for (i=0; i < size; i++) { biggest = point_compare(biggest, points + i); } return biggest; } However, there are a handful of disadvantages in using them: They pollute the main namespace (see below), however this is easily overcome with prefixing a library name to the type name. Harder to figure out the aliased type (having to scan/grep through code), though most IDEs provide this lookup automatically. Typedefs do not really "hide" anything in a struct or union — members are still accessible (account.balance). To really hide struct members, one needs to use 'incompletely-declared' structs. /* Example for namespace clash */ typedef struct account { float balance; } account; struct account account; /* possible */ account account; /* error */

See also[edit] Bit field Composite data type Flexible array member Passive data structure Union type

References[edit] ^ C struct memory layout? - Stack Overflow ^ 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.  ^ Parameter passing in C# ^ Kelley, Al; Pohl, Ira (2004). A Book On C: Programming in C (Fourth ed.). p. 418. ISBN 0-201-18399-4.  ^ "IBM Linux compilers. Initialization of structures and unions".  ^ "The New C Standard, §6.7.8 Initialization".  Retrieved from "" Categories: C (programming language)Hidden categories: Wikipedia articles needing style editing from June 2016All articles needing style editing

Navigation menu Personal tools Not logged inTalkContributionsCreate accountLog in Namespaces ArticleTalk Variants Views ReadEditView history More Search Navigation Main pageContentsFeatured contentCurrent eventsRandom articleDonate to WikipediaWikipedia store Interaction HelpAbout WikipediaCommunity portalRecent changesContact page Tools What links hereRelated changesUpload fileSpecial pagesPermanent linkPage informationWikidata itemCite this page Print/export Create a bookDownload as PDFPrintable version Languages ČeštinaDeutschفارسی한국어日本語NorskPolskiРусский中文 Edit links This page was last edited on 26 January 2018, at 15:28. Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. By using this site, you agree to the Terms of Use and Privacy Policy. Wikipedia® is a registered trademark of the Wikimedia Foundation, Inc., a non-profit organization. Privacy policy About Wikipedia Disclaimers Contact Wikipedia Developers Cookie statement Mobile view (window.RLQ=window.RLQ||[]).push(function(){mw.config.set({"wgPageParseReport":{"limitreport":{"cputime":"0.128","walltime":"0.193","ppvisitednodes":{"value":515,"limit":1000000},"ppgeneratednodes":{"value":0,"limit":1500000},"postexpandincludesize":{"value":11441,"limit":2097152},"templateargumentsize":{"value":386,"limit":2097152},"expansiondepth":{"value":12,"limit":40},"expensivefunctioncount":{"value":1,"limit":500},"entityaccesscount":{"value":0,"limit":400},"timingprofile":["100.00% 165.599 1 -total"," 44.00% 72.866 1 Template:Reflist"," 36.55% 60.521 1 Template:Manual"," 20.86% 34.552 1 Template:Cite_journal"," 17.00% 28.156 1 Template:Ambox"," 9.60% 15.899 1 Template:Main_article"," 7.17% 11.870 2 Template:Cite_web"," 6.67% 11.045 1 Template:DMCA"," 5.88% 9.737 1 Template:Dated_maintenance_category"," 4.83% 7.995 1 Template:Cite_book"]},"scribunto":{"limitreport-timeusage":{"value":"0.054","limit":"10.000"},"limitreport-memusage":{"value":2730603,"limit":52428800}},"cachereport":{"origin":"mw1321","timestamp":"20180218071731","ttl":1900800,"transientcontent":false}}});});(window.RLQ=window.RLQ||[]).push(function(){mw.config.set({"wgBackendResponseTime":291,"wgHostname":"mw1321"});});

Struct_(C_programming_language) - Photos and All Basic Informations

Struct_(C_programming_language) More Links

Wikipedia:What Wikipedia Is NotWikipedia:Neutral Point Of ViewHelp:Maintenance Template RemovalC Programming LanguageComposite Data TypeRecord (computer Science)Pointer (computer Programming)Assembly LanguageSizeofPrimitive Data TypeWord (computer Architecture)C++C++ ClassesALGOL 68C Sharp (programming Language)Visual Basic .NETClass (computer Programming)C++C++ ClassesAccess ModifiersAccess ModifiersTypedefStatic Memory AllocationDereference OperatorNull PointerTypedefTypedefPOSIXGrepOpaque PointerBit FieldComposite Data TypeFlexible Array MemberPassive Data StructureUnion TypeDennis RitchieDigital Object IdentifierInternational Standard Book NumberSpecial:BookSources/0-201-18399-4Help:CategoryCategory:C (programming Language)Category:Wikipedia Articles Needing Style Editing From June 2016Category:All Articles Needing Style EditingDiscussion About Edits From This IP Address [n]A List Of Edits Made From This IP Address [y]View The Content Page [c]Discussion About The Content Page [t]Edit This Page [e]Visit The Main Page [z]Guides To Browsing WikipediaFeatured Content – The Best Of WikipediaFind Background Information On Current EventsLoad A Random Article [x]Guidance On How To Use And Edit WikipediaFind Out About WikipediaAbout The Project, What You Can Do, Where To Find ThingsA List Of Recent Changes In The Wiki [r]List Of All English Wikipedia Pages Containing Links To This Page [j]Recent Changes In Pages Linked From This Page [k]Upload Files [u]A List Of All Special Pages [q]Wikipedia:AboutWikipedia:General Disclaimer

view link view link view link view link view link