Structure
C Prog
C programming, a struct (or structure) is a collection of variables (can be of different types) under a
single name.
Define Structures
struct structureName
{
dataType member1; dataType
member2; ...
};
struct MyStructure // Structure declaration
{
int myNum; // Member (int variable)
char myLetter; // Member (char variable)
}; // End the structure with a semicolon
To access the structure, you must create a variable of it.
Use the struct keyword inside the main() method,
followed by the name of the structure and then the name of the structure variable :
Create a struct variable with the name "s1"
struct myStructure {
int myNum;
char myLetter;
};
int main() {
struct myStructure s1;
return 0;
}
Access Structure Members To access members of a structure, use the dot syntax (.):
// Create a structure called myStructure
struct myStructure
{
int myNum;
char myLetter;
};
int main() {
// Create a structure variable of myStructure called s1
struct myStructure s1;
// Assign values to members of s1
s1.myNum = 13;
s1.myLetter = 'B';
// Print values
printf("My number: %d\n", s1.myNum);
printf("My letter: %c\n", s1.myLetter);
return 0;
}
Now you can easily create multiple structure variables with different values
// Create different struct variables
struct myStructure s1;
struct myStructure s2;
// Assign values to different struct variables
s1.myNum = 13;
s1.myLetter = 'B';
s2.myNum = 20;
s2.myLetter = 'C';
#include <stdio.h>
// Assign values to different struct variables
s1.myNum = 13;
struct myStructure s1.myLetter = 'B';
{
int myNum; s2.myNum = 20;
char myLetter; s2.myLetter = 'C';
}; // Print values
printf("s1 number: %d\n", s1.myNum);
int main() printf("s1 letter: %c\n", s1.myLetter);
{
// Create different struct variables printf("s2 number: %d\n", s2.myNum);
printf("s2 letter: %c\n", s2.myLetter);
struct myStructure s1;
struct myStructure s2; return 0;
}
You can also assign one structure to another.
Copy Structures In the following example,
the values of s1 are copied to s2:
struct myStructure s1 = {13, 'B', "Some text"};
struct myStructure s2;
s2 = s1;
Another way
of creating
a struct variable is:
#include <stdio.h>
#include <string.h>
// create struct with person1 variable
struct Person {
char name[50];
int citNo; // print struct variables
float salary; printf("Name: %s\n", person1.name);
} person1;
printf("Citizenship No.: %d\n", person1.citNo);
int main()
{ printf("Salary: %.2f", person1.salary);
// assign value to name of person1
strcpy(person1.name, "George Orwell"); return 0;
}
// assign values to other person1 variables
person1.citNo = 1984;
person1. salary = 2500;