Open navigation menu
Close suggestions
Search
Search
en
Change Language
Upload
Sign in
Sign in
Download free for days
0 ratings
0% found this document useful (0 votes)
19 views
C Structure
Uploaded by
apc78044
AI-enhanced title
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
Download now
Download
Save c structure For Later
Download
Save
Save c structure For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
0 ratings
0% found this document useful (0 votes)
19 views
C Structure
Uploaded by
apc78044
AI-enhanced title
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
Download now
Download
Save c structure For Later
Carousel Previous
Carousel Next
Save
Save c structure For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
Download now
Download
You are on page 1
/ 14
Search
Fullscreen
C Structures Read) (_Courses The structure in C is a user-defined data type that can be used to group Cra) C roe) (Practice) (video) (sobs ) items of possibly different types into a single type. The struct keyword is used to define the structure in the C programming language. The items in the structure are called its member and they can be of any valid data type Structure in C Struct keyword relat kets struct geeksforgeeks a char __name [10: aC TET, eae float salary; C Structure Declaration We have to declare structure in C before using it in our program. In structure declaration, we specify its member variables along with their datatype. We can use the struct keyword to declare the structure in C using the following syntax:struct structure_name { data_type member_name1; data_type member_name1; & The above syntax is also called a structure template or structure prototype and no memory is allocated to the structure in the declaration. C Structure Definition To use structure in our program, we have to define its instance. We can do that by creating variables of the structure type. We can define structure variables using two methods: 1. Structure Variable Declaration with Structure Template struct structure_name { data_type member_name1; data_type member_name1; }variable1, varaible2, 2. Structure Variable Declaration after Structure Template // structure declared beforehandstruct structure_name variable1, variable2, .. Access Structure Members We can access structure members by using the (_..) dot operator. Syntax structure_name.member1; strcuture_name.member2; In the case where we have a pointer to the structure, we can also use the arrow operator to access the members. Initialize Structure Members Structure members cannot be initialized with the declaration. For example, the following C program fails in the compilation struct Point { int x ®; // COMPILER ERROR: cannot initialize members here ®; // COMPILER ERROR: cannot initialize members here int y % The reason for the above error is simple. When a datatype is declared, no memory is allocated for it. Memory is allocated only when variables are created. We can initialize structure members in 3 ways which are as follows: 1. Using Assignment Operator. 2. Using Initializer List. 3. Using Designated Initializer List. \/ 1 Initialization using Assignment Operator struct structure_name str; str.member1 = value1; str.member2 = value2; str.member3 = value3;2. Initialization using Initializer List struct structure_name str = { valuel, value2, value3 }; In this type of initialization, the values are assigned in sequential order as they are declared in the structure template. 3. Initialization using Designated Initializer List \- ges Designated Initialization allows structure members to be initialized in any order. This feature has been added in the C99 standard. struct structure_name str = { .member1 = valuel, .member2 = value2, -member3 = value3 }; The Designated Initialization is only supported in C but not in C++. Example of Structure in C The following C program shows how to use structures c // © program to illustrate the use of structures include
// declaring structure with name str1 struct stri { int 45 char c; float f; char s(30]; u // declaring structure with name str2 struct str2 { int ii; char ce; float ff; } var; // variable declaration with structure template // river codeint main() t // variable declaration after structure template // initialization with initializer list and designated // initializer list struct stri vari = { 1, var25 struct str2 var3 = { .ff = 5.00, .ii = 5, .cc = ‘a! }5 A‘, 1.8, "GeeksforGeeks” }, // copying structure using assignment operator var2 = vart; print#("Struct 1:\n\ti = Xd, ¢ = Kc, f = BF, 5 varl.i, varl.c, varl.f, vari.s); printf("Struct 2:\n\ti = %d, ¢ = Xc, f = Xf, s = Xs\n", var2.i, var2.c, var2.f, var2.s)5 print#("Struct 3\n\ti = %d, ¢ = Kc, f = XF\n", var3.ii var3.cc, var3.ff); Xs\n", return 0; Output Struct 1: i=1, c= A, f = 1.000000, s = GeeksforGeeks Struct 2: 1.000000, s GeeksforGeeks 5.200000 typedef for Structures The typedef keyword is used to define an alias for the already existing datatype. In structures, we have to use the struct keyword along with the structure name to define the variables. Sometimes, this increases the length and complexity of the code. We can use the typedef to define some new shorter name for the structure. Example c// © Program to illustrate the use of typedef with // structures #include
// defining structure struct str1 { int a; ub // defining new name for str1 typedef struct str stra; // another way of using typedef with structures typedef struct str2 { int x; } str2; int main() t // creating structure variables using new names str1 varl = { 28 }; str2 var2 = { 314 }5 printf("vart.a print#(*var2.x Xd\n", vard.a); Bd", var2.x)5 return @; Output varl.a = 20 314 var2.x Nested Structures C language allows us to insert one structure into another as a member. This process is called nesting and such structures are called nested structures. There are two ways in which we can nest one structure into another: 1. Embedded Structure Nesting In this method, the structure being nested is also declared inside the parent structure.Example struct parent { int member1; struct member_str member2 { int member_stri; char member_str2; 2. Separate Structure Nesting In this method, two structures are declared separately and then the member structure is nested inside the parent structure. Example struct member_str { int member_str1; char member_str2; struct parent { int member1; struct member_str member2; One thing to note here is that the declaration of the structure should always be present before its definition as a structure member. For example, the declaration below is invalid as the struct mem is not defined when it is declared inside the parent structure. struct parent { struct mem a; % struct mem (int var; 3 Accessing Nested Members We can access nested Members by using the same (. ) dot operator two times as shown: str_parent.str_child.member; Example of Structure Nesting c // © Program to illustrate structure nesting along with // forward declaration include
// child structure declaration struct child { int x; char c; us // parent structure declaration struct parent { int a; struct child bs // driver code int main() t struct parent varl = { 25, 195, // accessing and printing nested members printf("varl.a = d\n", vard.a); printf(*varl.b.x = %d\n", vard.b.x)5 printf(*vari.b.c = %c", vart.b.c); return 0;Output varl.a = 25 vari.b.x = 195 varl.b.c = A Structure Pointer in C We can define a pointer that points to the structure like any other variable. Such pointers are generally called Structure Pointers. We can access the members of the structure pointed by the structure pointer using the (=>) arrow operator. Example of Structure Pointer c // © program to illustrate the structure pointer include
// steucture declaration struct Point { int x, y3 int main() { struct Point str = (1, 2 }5 // p2 is a pointer to structure pt struct Point* ptr = astr; // Accessing structure members using structure pointer printé("%d %d", ptr->x, ptr->y); return @; y OutputL-Getr- Referential Structures L TI The sel eferential structures in C are those structures that contain references to the same type as themselves i.e. they contain a member of the type pointer pointing to the same structure type. Example of Self-Referential Structures struct structure_name { data_type member1; data_type member2; struct structure_name* str; Cc // © program to illustrate the self referential structures #include
// structure template typedef struct str { int mem; int mem2; struct str* next; ystr; // driver code int main() { str vara = (1, 2, NULL }5 str var2 = { 10, 20, NULL }; // assigning the address of var2 to vari.next vard.next = &var2; // pointer to vard str ptr = avart; // accessing var2 menbers using var1 printf("var2.men1: %d\nvar2.men2: %d", ptrd-snext->mem1, ptri-snext->men2); return @;Output var2.mem1: 10 var2.mem2: 20 Such kinds of structures are used in different data structures such as to define the nodes of linked lists, trees, etc. 7) C Structure Padding and Packing “Technically, the size of the structure in C should be the sum of the sizes ofits : structure : a 1. Using #pragma pack(1) 2. Using __attribute((packed))__ Example of Structure Padding and Packing fa} // © program to illustrate structure padding and packing #include
// structure with padding struct str { char 5 int i; ub struct str2 { char cs int i; } _attribute((packed)) __; // using structure packing// driver code int main() t printf ("Size of str: %d\n", sizeof(struct str1)); printf("Size of str2: %d\n", sizeof(struct str2)); return 03 Output Size of stri: 8 Size of str2: 5 As we can see, the size of the structure is varied when structure packing is performed. To know more about structure padding and packing, refer to this article Structure Member Alignment, Padding and Data Packing. Fields 90% Refund @Courses C CBasics CDataTypes COperators Cinputand Output CControlFlow WE HSH WE RUW WHE HHOAIHUIT SoHYuH UF Une HHEHWEH We Lar Use WIE HWS specify the size and reduce memory consumption. Syntax of Bit Fields struct structure_name { data_type menber_name: width of bit-field; & Example of Bit Fields c J/ © Program to illustrate bit fields in structures include
// declaring structure for reference struct str {int a; char c; ‘ // structure with bit fields struct str2 { int a : 24; // size of ‘a’ is 3 bytes = 24 bits char c; u // driver code int main() { printf("Size of Str1: %d\nSize of str2: %¢", sizeof(struct str1), sizeof(struct str2)); return 05 Output Size of Stri: 8 Size of Str2: 4 As we can see, the size of the structure is reduced when using the bit field to define the max size of the member ‘a’. Uses of Structure in C C structures are used for the following: 1. The structure can be used to define the custom data types that can be used to create some complex data types such as dates, time, complex numbers, etc. which are not present in the language. 2. It can also be used in data organization where a large amount of data can be stored in different fields 3. Structures are used to create data structures such as trees, linked lists, etc. 4. They can also be used for returning multiple values from a function. Limitations of C Structures In C language, structures provide a method for packing together data of different types. A Structure is a helpful tool to handle a group of logicallyrelated data items. However, C structures also have some limitations. + Higher Memory Consumption: It is due to structure padding. + No Data Hiding: C Structures do not permit data hiding. Structure members can be accessed by any function, anywhere in the scope of the structure. + Functions inside Structure: C structures do not permit functions inside the structure so we cannot provide the associated functions. * Static Members: C Structure cannot have static members inside its body. * Construction creation in Structure: Structures in C cannot have a constructor inside Structures. Related Articles * C Structures vs C++ Structure Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now! Get paid for your published articles and stand a chance to win tablet, smartwatch and exclusive GfG goodies! Submit your entries in Dev Scripter 2024 today Participate in Three 90 Challenge! Enroll in any GeeksforGeeks course and get 90% refund by completing 90% course. Explore offer now. Last Updated : 06 May, 2023 an. Previous Next restrict keyword in C dot (.) Operator in C Share your thoughts in the comments $d Your Comme
You might also like
The Subtle Art of Not Giving a F*ck: A Counterintuitive Approach to Living a Good Life
From Everand
The Subtle Art of Not Giving a F*ck: A Counterintuitive Approach to Living a Good Life
Mark Manson
4/5 (6135)
Principles: Life and Work
From Everand
Principles: Life and Work
Ray Dalio
4/5 (628)
The Gifts of Imperfection: Let Go of Who You Think You're Supposed to Be and Embrace Who You Are
From Everand
The Gifts of Imperfection: Let Go of Who You Think You're Supposed to Be and Embrace Who You Are
Brene Brown
4/5 (1148)
Never Split the Difference: Negotiating As If Your Life Depended On It
From Everand
Never Split the Difference: Negotiating As If Your Life Depended On It
Chris Voss
4.5/5 (935)
The Glass Castle: A Memoir
From Everand
The Glass Castle: A Memoir
Jeannette Walls
4/5 (8215)
Grit: The Power of Passion and Perseverance
From Everand
Grit: The Power of Passion and Perseverance
Angela Duckworth
4/5 (631)
Sing, Unburied, Sing: A Novel
From Everand
Sing, Unburied, Sing: A Novel
Jesmyn Ward
4/5 (1253)
The Perks of Being a Wallflower
From Everand
The Perks of Being a Wallflower
Stephen Chbosky
4/5 (8365)
Shoe Dog: A Memoir by the Creator of Nike
From Everand
Shoe Dog: A Memoir by the Creator of Nike
Phil Knight
4.5/5 (860)
Her Body and Other Parties: Stories
From Everand
Her Body and Other Parties: Stories
Carmen Maria Machado
4/5 (877)
The Hard Thing About Hard Things: Building a Business When There Are No Easy Answers
From Everand
The Hard Thing About Hard Things: Building a Business When There Are No Easy Answers
Ben Horowitz
4.5/5 (361)
Hidden Figures: The American Dream and the Untold Story of the Black Women Mathematicians Who Helped Win the Space Race
From Everand
Hidden Figures: The American Dream and the Untold Story of the Black Women Mathematicians Who Helped Win the Space Race
Margot Lee Shetterly
4/5 (954)
Steve Jobs
From Everand
Steve Jobs
Walter Isaacson
4/5 (2923)
Elon Musk: Tesla, SpaceX, and the Quest for a Fantastic Future
From Everand
Elon Musk: Tesla, SpaceX, and the Quest for a Fantastic Future
Ashlee Vance
4.5/5 (484)
The Emperor of All Maladies: A Biography of Cancer
From Everand
The Emperor of All Maladies: A Biography of Cancer
Siddhartha Mukherjee
4.5/5 (277)
A Man Called Ove: A Novel
From Everand
A Man Called Ove: A Novel
Fredrik Backman
4.5/5 (4973)
Angela's Ashes: A Memoir
From Everand
Angela's Ashes: A Memoir
Frank McCourt
4.5/5 (444)
Brooklyn: A Novel
From Everand
Brooklyn: A Novel
Colm Toibin
3.5/5 (2061)
The Art of Racing in the Rain: A Novel
From Everand
The Art of Racing in the Rain: A Novel
Garth Stein
4/5 (4281)
The Yellow House: A Memoir (2019 National Book Award Winner)
From Everand
The Yellow House: A Memoir (2019 National Book Award Winner)
Sarah M. Broom
4/5 (100)
The Little Book of Hygge: Danish Secrets to Happy Living
From Everand
The Little Book of Hygge: Danish Secrets to Happy Living
Meik Wiking
3.5/5 (447)
Yes Please
From Everand
Yes Please
Amy Poehler
4/5 (1988)
Devil in the Grove: Thurgood Marshall, the Groveland Boys, and the Dawn of a New America
From Everand
Devil in the Grove: Thurgood Marshall, the Groveland Boys, and the Dawn of a New America
Gilbert King
4.5/5 (278)
The World Is Flat 3.0: A Brief History of the Twenty-first Century
From Everand
The World Is Flat 3.0: A Brief History of the Twenty-first Century
Thomas L. Friedman
3.5/5 (2283)
Bad Feminist: Essays
From Everand
Bad Feminist: Essays
Roxane Gay
4/5 (1068)
The Woman in Cabin 10
From Everand
The Woman in Cabin 10
Ruth Ware
3.5/5 (2641)
A Tree Grows in Brooklyn
From Everand
A Tree Grows in Brooklyn
Betty Smith
4.5/5 (1936)
The Outsider: A Novel
From Everand
The Outsider: A Novel
Stephen King
4/5 (1994)
The Sympathizer: A Novel (Pulitzer Prize for Fiction)
From Everand
The Sympathizer: A Novel (Pulitzer Prize for Fiction)
Viet Thanh Nguyen
4.5/5 (125)
Team of Rivals: The Political Genius of Abraham Lincoln
From Everand
Team of Rivals: The Political Genius of Abraham Lincoln
Doris Kearns Goodwin
4.5/5 (1912)
A Heartbreaking Work Of Staggering Genius: A Memoir Based on a True Story
From Everand
A Heartbreaking Work Of Staggering Genius: A Memoir Based on a True Story
Dave Eggers
3.5/5 (692)
Wolf Hall: A Novel
From Everand
Wolf Hall: A Novel
Hilary Mantel
4/5 (4074)
On Fire: The (Burning) Case for a Green New Deal
From Everand
On Fire: The (Burning) Case for a Green New Deal
Naomi Klein
4/5 (75)
Fear: Trump in the White House
From Everand
Fear: Trump in the White House
Bob Woodward
3.5/5 (830)
Manhattan Beach: A Novel
From Everand
Manhattan Beach: A Novel
Jennifer Egan
3.5/5 (901)
Rise of ISIS: A Threat We Can't Ignore
From Everand
Rise of ISIS: A Threat We Can't Ignore
Jay Sekulow
3.5/5 (143)
John Adams
From Everand
John Adams
David McCullough
4.5/5 (2544)
The Light Between Oceans: A Novel
From Everand
The Light Between Oceans: A Novel
M L Stedman
4.5/5 (790)
The Unwinding: An Inner History of the New America
From Everand
The Unwinding: An Inner History of the New America
George Packer
4/5 (45)
Little Women
From Everand
Little Women
Louisa May Alcott
4/5 (105)
The Constant Gardener: A Novel
From Everand
The Constant Gardener: A Novel
John le Carré
3.5/5 (109)