You are on page 1of 6

ADDITIONAL KNOWLEDGE

Structures in C

John Kenneth B. Musico

CE 28
Analytical & Computational Institute of Civil Engineering
Methods in CE III
Structures

let’s say…
▪ You want to store information about a person: his/her name,
citizenship number and salary.
▪ You can create different variables name, citNo and salary to store
these information separately.
▪ What if you need to store information of more than one person?
▪ Now, you need to create different variables for each information per
person: name1, citNo1, salary1, name2, citNo2, salary2 etc.
▪ A better approach would be to have a collection of all related
information under a single name Person structure, and use it for
every person.

CE 28 Analytical & Computational Methods in CE III 2


Structures

Structure
▪ a collection of variables (can be of different types) under a single
name.

How to create one? ’struct’ keyword is used to create a structure.


struct structure_name for our example
{ struct Person
data_type member1; {
data_type member2; char name[50];
. int citNo;
. float salary;
data_type memeber; };
};

CE 28 Analytical & Computational Methods in CE III 3


Structures

How to declare structure variables?


struct Person
{
char name[50];
int citNo;
float salary;
};
YES! You can declare
main()
{ an array of structures!
struct Person person1, person2, p[20];
.
.
}

CE 28 Analytical & Computational Methods in CE III 4


Structures

How to simplify the syntax of a structure?


By using the keyword ‘typedef’

struct Person
{
char name[50];
int citNo;
float salary;
} typedef struct Person pipz;

main()
{
pipz person1, person2, p[20];
.
.
}

CE 28 Analytical & Computational Methods in CE III 5


Structures

How to access structure elements?


Structure members are accessed using dot (.) operator.

struct Person
{
char name[50];
int citNo;
float salary;
} typedef struct Person pipz;

main()
{
pipz person1, person2, p[20];
person1.salary = 30,000;
scanf(“%d”, &person1.citNo)
}

CE 28 Analytical & Computational Methods in CE III 6

You might also like