C Language | Structure Declarations | Structures - struct
Structures combine values of different types into one object.
Defining a Structure
Use struct to define related members.
struct tag-name {
type member1;
type member2;
};
Create an instance with the tag name and access members with ..
Code 1
#include <stdio.h>
struct Point { int x , y; };
int main() {
struct Point pt = { 100 , 50 };
printf("pt.x = %d : pt.y = %d\n" , pt.x , pt.y);
return 0;
}
Each instance has independent storage.
struct Point pt1 = { 100 , 50 };
struct Point pt2 = { 200 , 100 };

An anonymous structure omits the tag and can only be used where it is declared.
struct { int x , y; } pt = { 100 , 35 };
Assigning Structures
Structures of the same type can be assigned. Every member is copied.
Code 2
#include <stdio.h>
struct Point { int x , y; };
int main() {
struct Point pt1 = { 200 , 100 } , pt2 = { 0 };
pt2 = pt1;
printf("pt2.x = %d : pt2.y = %d\n" , pt2.x , pt2.y);
return 0;
}
Structures can also be passed to and returned from functions.
Code 3
#include <stdio.h>
struct Point { int x , y; };
struct Point sizeToPoint(struct Point origin , int width , int height) {
struct Point result = { origin.x + width , origin.y + height };
return result;
}
int main() {
struct Point location = { 100 , 100 };
printf("Right = %d\n" , sizeToPoint(location , 200 , 40).x);
return 0;
}
Passing a large structure by value copies its members. Use a pointer when copying is unnecessary.