0% found this document useful (0 votes)
6 views29 pages

Unit 1

The document explains C structures, including how to define, create, and access structure variables, as well as how to use typedef to simplify structure declarations. It also covers nested structures, passing structures to functions, and the differences between structures and unions. Additionally, it discusses the typedef keyword for creating aliases for existing data types, particularly in the context of structures.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views29 pages

Unit 1

The document explains C structures, including how to define, create, and access structure variables, as well as how to use typedef to simplify structure declarations. It also covers nested structures, passing structures to functions, and the differences between structures and unions. Additionally, it discusses the typedef keyword for creating aliases for existing data types, particularly in the context of structures.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 29

C structures

In C programming, a struct (or structure) is a collection of variables


(can be of different types) under a single name.
Define Structures
Before you can create structure variables, you need to define its data
type. To define a struct, the struct keyword is used.
Syntax of struct
struct structureName {
dataType member1;
dataType member2;
...
};
For example,
struct Person {
char name[50];
int citNo;
float salary;
};
Here, a derived type struct Person is defined. Now, you can create
variables of this type.
Create struct Variables
When a struct type is declared, no storage or memory is allocated. To
allocate memory of a given structure type and work with it, we need
to create variables.
Here's how we create structure variables:
struct Person {
// code
};
int main() {
struct Person person1, person2, p[20];
return 0;
}
Another way of creating a struct variable is:
struct Person {
// code
} person1, person2, p[20];
In both cases,
person1 and person2 are struct Person variables
p[] is a struct Person array of size 20.
Access Members of a Structure
There are two types of operators used for accessing members of a
structure.
. - Member operator
-> - Structure pointer operator (will be discussed in the next
tutorial)
Suppose, you want to access the salary of person2. Here's how you
can do it.
person2.salary
Example 1: C structs
#include <stdio.h>
#include <string.h>
// create struct with person1 variable
struct Person {
char name[50];
int citNo;
float salary;
} person1;
int main() {
// assign value to name of person1
strcpy(person1.name, "George Orwell");
// assign values to other person1 variables
person1.citNo = 1984;
person1. salary = 2500;
// print struct variables
printf("Name: %s\n", person1.name);
printf("Citizenship No.: %d\n", person1.citNo);
printf("Salary: %.2f", person1.salary);
return 0;
}
Output
Name: George Orwell
Citizenship No.: 1984
Salary: 2500.00
In this program, we have created a struct named Person. We have
also created a variable of Person named person1.
In main(), we have assigned values to the variables defined in Person
for the person1 object.
strcpy(person1.name, "George Orwell");
person1.citNo = 1984;
person1. salary = 2500;
Notice that we have used strcpy() function to assign the value to
person1.name.
This is because name is a char array (C-string) and we cannot use the
assignment operator = with it after we have declared the string.
Finally, we printed the data of person1.
Keyword typedef
We use the typedef keyword to create an alias name for data types. It
is commonly used with structures to simplify the syntax of declaring
variables.
For example, let us look at the following code:
struct Distance{
int feet;
float inch;
};
int main() {
struct Distance d1, d2;
}
We can use typedef to write an equivalent code with a simplified
syntax:
typedef struct Distance {
int feet;
float inch;
} distances;
int main() {
distances d1, d2;
}
Example 2: C typedef
#include <stdio.h>
#include <string.h>
// struct with typedef person
typedef struct Person {
char name[50];
int citNo;
float salary;
} person;
int main() {
// create Person variable
person p1;
// assign value to name of p1
strcpy(p1.name, "George Orwell");
// assign values to other p1 variables
p1.citNo = 1984;
p1. salary = 2500;
// print struct variables
printf("Name: %s\n", p1.name);
printf("Citizenship No.: %d\n", p1.citNo);
printf("Salary: %.2f", p1.salary);
return 0;
}
Output
Name: George Orwell
Citizenship No.: 1984
Salary: 2500.00
Here, we have used typedef with the Person structure to create an
alias person.
// struct with typedef person
typedef struct Person {
// code
} person;
Now, we can simply declare a Person variable using the person alias:
// equivalent to struct Person p1
person p1;
Nested Structures
You can create structures within a structure in C programming. For
example,
struct complex {
int imag;
float real;
};
struct number {
struct complex comp;
int integers;
} num1, num2;
Suppose, you want to set imag of num2 variable to 11. Here's how
you can do it:
num2.comp.imag = 11;
Example 3: C Nested Structures
#include <stdio.h>
struct complex {
int imag;
float real;
};
struct number {
struct complex comp;
int integer;
} num1;
int main() {
// initialize complex variables
num1.comp.imag = 11;
num1.comp.real = 5.25;
// initialize number variable
num1.integer = 6;
// print struct variables
printf("Imaginary Part: %d\n", num1.comp.imag);
printf("Real Part: %.2f\n", num1.comp.real);
printf("Integer: %d", num1.integer);
return 0;
}
Output
Imaginary Part: 11
Real Part: 5.25
Integer: 6
Why structs in C?
Suppose 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 this information.
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.
C Structure and Function
Similar to variables of built-in types, you can also pass structure
variables to a function.
Passing structs to functions
Here's how you can pass structures to a function
#include <stdio.h>
struct student {
char name[50];
int age;
};
// function prototype
void display(struct student s);
int main() {
struct student s1;
printf("Enter name: ");
// read string input from the user until \n is entered
// \n is discarded
scanf("%s", s1.name);
printf("Enter age: ");
scanf("%d", &s1.age);
display(s1); // passing struct as an argument
return 0;
}
void display(struct student s) {
printf("\nDisplaying information\n");
printf("Name: %s", s.name);
printf("\nAge: %d", s.age); }
Output
Enter name: Bond
Enter age: 13
Displaying information
Name: Bond
Age: 13
Here, a struct variable s1 of type struct student is created. The
variable is passed to the display() function using display(s1);
statement.
Return struct from a function
Here's how you can return structure from a function:
#include <stdio.h>
struct student
{
char name[50];
int age;
};
// function prototype
struct student getInformation();
int main()
{
struct student s;
s = getInformation();
printf("\nDisplaying information\n");
printf("Name: %s", s.name);
printf("\nRoll: %d", s.age);
return 0;
}
struct student getInformation()
{
struct student s1;
printf("Enter name: ");
scanf ("%[^\n]%*c", s1.name);
printf("Enter age: ");
scanf("%d", &s1.age);
return s1;
}
Here, the getInformation() function is called using s =
getInformation(); statement. The function returns a structure of type
struct student. The returned structure is displayed from the main()
function.
Notice that, the return type of getInformation() is also struct student.
Passing struct by reference
You can also pass structs by reference (in a similar way like you pass
variables of built-in type by reference). We suggest you to read pass
by reference tutorial before you proceed.
During pass by reference, the memory addresses of struct variables
are passed to the function.
#include <stdio.h>
typedef struct Complex
{
float real;
float imag;
} complex;
void addNumbers(complex c1, complex c2, complex *result);
int main()
{
complex c1, c2, result;
printf("For first number,\n");
printf("Enter real part: ");
scanf("%f", &c1.real);
printf("Enter imaginary part: ");
scanf("%f", &c1.imag);
printf("For second number, \n");
printf("Enter real part: ");
scanf("%f", &c2.real);
printf("Enter imaginary part: ");
scanf("%f", &c2.imag);
addNumbers(c1, c2, &result);
printf("\nresult.real = %.1f\n", result.real);
printf("result.imag = %.1f", result.imag);
return 0;
}
void addNumbers(complex c1, complex c2, complex *result)
{
result->real = c1.real + c2.real;
result->imag = c1.imag + c2.imag;
}
Output
For first number,
Enter real part: 1.1
Enter imaginary part: -2.4
For second number,
Enter real part: 3.4
Enter imaginary part: -3.2
result.real = 4.5
result.imag = -5.6
In the above program, three structure variables c1, c2 and the
address of result is passed to the addNumbers() function. Here,
result is passed by reference.
When the result variable inside the addNumbers() is altered,
the result variable inside the main() function is also altered
accordingly.
C Unions
A union is a user-defined type similar to structs in C except for one
key difference.
Structures allocate enough space to store all their members, whereas
unions can only hold one member value at a time.
How to define a union?
We use the union keyword to define unions. Here's an example:
union car
{
char name[50];
int price;
};
The above code defines a derived type union car.
Create union variables
When a union is defined, it creates a user-defined type. However, no
memory is allocated. To allocate memory for a given union type and
work with it, we need to create variables.
Here's how we create union variables.
union car
{
char name[50];
int price;
};
int main()
{
union car car1, car2, *car3;
return 0;
}
Another way of creating union variables is:
union car
{
char name[50];
int price;
} car1, car2, *car3;
In both cases, union variables car1, car2, and a union pointer car3 of
union car type are created.
Access members of a union
We use the . operator to access members of a union. And to access
pointer variables, we use the -> operator.
In the above example,
 To access price for car1, car1.price is used.
 To access price using car3, either (*car3).price or car3->price
can be used.
Difference between unions and structures
Let's take an example to demonstrate the difference between unions
and structures:
#include <stdio.h>
union unionJob
{
//defining a union
char name[32];
float salary;
int workerNo;
} uJob;
struct structJob
{
char name[32];
float salary;
int workerNo;
} sJob;
int main()
{
printf("size of union = %d bytes", sizeof(uJob));
printf("\nsize of structure = %d bytes", sizeof(sJob));
return 0;
}
Output
size of union = 32
size of structure = 40
Why this difference in the size of union and structure variables?
Here, the size of sJob is 40 bytes because
 the size of name[32] is 32 bytes
 the size of salary is 4 bytes
 the size of workerNo is 4 bytes
However, the size of uJob is 32 bytes. It's because the size of a union
variable will always be the size of its largest element. In the above
example, the size of its largest element, (name[32]), is 32 bytes.
With a union, all members share the same memory.
Example: Accessing Union Members
#include <stdio.h>
union Job {
float salary;
int workerNo;
} j;
int main() {
j.salary = 12.3;
// when j.workerNo is assigned a value,
// j.salary will no longer hold 12.3
j.workerNo = 100;
printf("Salary = %.1f\n", j.salary);
printf("Number of workers = %d", j.workerNo);
return 0;
}
Output
Salary = 0.0
Number of workers = 100
typedef in C
The typedef is a keyword used in C programming to provide some
meaningful names to the already existing variable in the C program.
It behaves similarly as we define the alias for the commands. In
short, we can say that this keyword is used to redefine the name of
an already existing variable.
Syntax of typedef
1. typedef <existing_name> <alias_name>
n the above syntax, 'existing_name' is the name of an already
existing variable while 'alias name' is another name given to the
existing variable.
For example, suppose we want to create a variable of type unsigned
int, then it becomes a tedious task if we want to declare multiple
variables of this type. To overcome the problem, we use a typedef
keyword.
1. typedef unsigned int unit;
In the above statements, we have declared the unit variable of type
unsigned int by using a typedef keyword.
Now, we can create the variables of type unsigned int by writing the
following statement:
1. unit a, b;
instead of writing:
1. unsigned int a, b;
Till now, we have observed that the typedef keyword provides a nice
shortcut by providing an alternative name for an already existing
variable. This keyword is useful when we are dealing with the long
data type especially, structure declarations.
Let's understand through a simple example.
1. #include <stdio.h>
2. int main()
3. {
4. typedef unsigned int unit;
5. unit i,j;
6. i=10;
7. j=20;
8. printf("Value of i is :%d",i);
9. printf("\nValue of j is :%d",j);
10. return 0;
11. }
Output
Value of i is :10
Value of j is :20
Using typedef with structures
Consider the below structure declaration:
1. struct student
2. {
3. char name[20];
4. int age;
5. };
6. struct student s1;
In the above structure declaration, we have created the variable of
student type by writing the following statement:
1. struct student s1;
The above statement shows the creation of a variable, i.e., s1, but
the statement is quite big. To avoid such a big statement, we use the
typedef keyword to create the variable of type student.
1. struct student
2. {
3. char name[20];
4. int age;
5. };
6. typedef struct student stud;
7. stud s1, s2;
In the above statement, we have declared the variable stud of type
struct student. Now, we can use the stud variable in a program to
create the variables of type struct student.
The above typedef can be written as:
1. typedef struct student
2. {
3. char name[20];
4. int age;
5. } stud;
6. stud s1,s2;
From the above declarations, we conclude that typedef keyword
reduces the length of the code and complexity of data types. It also
helps in understanding the program.
Let's see another example where we typedef the structure
declaration.
1. #include <stdio.h>
2. typedef struct student
3. {
4. char name[20];
5. int age;
6. }stud;
7. int main()
8. {
9. stud s1;
10. printf("Enter the details of student s1: ");
11. printf("\nEnter the name of the student:");
12. scanf("%s",&s1.name);
13. printf("\nEnter the age of student:");
14. scanf("%d",&s1.age);
15. printf("\n Name of the student is : %s", s1.name);
16. printf("\n Age of the student is : %d", s1.age);
17. return 0;
18. }
Output
Enter the details of student s1:
Enter the name of the student: Peter
Enter the age of student: 28
Name of the student is : Peter
Age of the student is : 28
Using typedef with pointers
We can also provide another name or alias name to the pointer
variables with the help of the typedef.
For example, we normally declare a pointer, as shown below:
1. int* ptr;
We can rename the above pointer variable as given below:
1. typedef int* ptr;
In the above statement, we have declared the variable of type int*.
Now, we can create the variable of type int* by simply using the 'ptr'
variable as shown in the below statement:
1. ptr p1, p2 ;
In the above statement, p1 and p2 are the variables of type 'ptr'.
Enum in C
The enum in C is also known as the enumerated type. It is a user-
defined data type that consists of integer values, and it provides
meaningful names to these values. The use of enum in C makes the
program easy to understand and maintain. The enum is defined by
using the enum keyword.
The following is the way to define the enum in C:
1. enum flag{integer_const1, integer_const2,.....integter_constN};
In the above declaration, we define the enum named as flag
containing 'N' integer constants. The default value of integer_const1
is 0, integer_const2 is 1, and so on. We can also change the default
value of the integer constants at the time of the declaration.
For example:
1. enum fruits{mango, apple, strawberry, papaya};
The default value of mango is 0, apple is 1, strawberry is 2, and
papaya is 3. If we want to change these default values, then we can
do as given below:
1. enum fruits{
2. mango=2,
3. apple=1,
4. strawberry=5,
5. papaya=7,
6. };
Enumerated type declaration
As we know that in C language, we need to declare the variable of a
pre-defined type such as int, float, char, etc. Similarly, we can declare
the variable of a user-defined data type, such as enum. Let's see how
we can declare the variable of an enum type.
Suppose we create the enum of type status as shown below:
1. enum status{false,true};
Now, we create the variable of status type:
1. enum status s; // creating a variable of the status type.
In the above statement, we have declared the 's' variable of type
status.
To create a variable, the above two statements can be written as:
1. enum status{false,true} s;
In this case, the default value of false will be equal to 0, and the value
of true will be equal to 1.
Let's create a simple program of enum.
1. #include <stdio.h>
2. enum weekdays{Sunday=1, Monday, Tuesday, Wednesday, Thur
sday, Friday, Saturday};
3. int main()
4. {
5. enum weekdays w; // variable declaration of weekdays type
6. w=Monday; // assigning value of Monday to w.
7. printf("The value of w is %d",w);
8. return 0;
9. }
In the above code, we create an enum type named as weekdays,
and it contains the name of all the seven days. We have assigned 1
value to the Sunday, and all other names will be given a value as
the previous value plus one.
Output

Let's demonstrate another example to understand the enum


more clearly.
1. #include <stdio.h>
2. enum months{jan=1, feb, march, april, may, june, july, august, s
eptember, october, november, december};
3. int main()
4. {
5. // printing the values of months
6. for(int i=jan;i<=december;i++)
7. {
8. printf("%d, ",i);
9. }
10. return 0;
11. }
In the above code, we have created a type of enum named as
months which consists of all the names of months. We have
assigned a '1' value, and all the other months will be given a value
as the previous one plus one. Inside the main() method, we have
defined a for loop in which we initialize the 'i' variable by jan, and
this loop will iterate till December.
Output

Why do we use enum?


The enum is used when we want our variable to have only a set of
values. For example, we create a direction variable. As we know
that four directions exist (North, South, East, West), so this
direction variable will have four possible values. But the variable
can hold only one value at a time. If we try to provide some
different value to this variable, then it will throw the compilation
error.
The enum is also used in a switch case statement in which we pass
the enum variable in a switch parenthesis. It ensures that the
value of the case block should be defined in an enum.
Let's see how we can use an enum in a switch case statement.
1. #include <stdio.h>
2. enum days{sunday=1, monday, tuesday, wednesday, thursday, fr
iday, saturday};
3. int main()
4. {
5. enum days d;
6. d=monday;
7. switch(d)
8. {
9. case sunday:
10. printf("Today is sunday");
11. break;
12. case monday:
13. printf("Today is monday");
14. break;
15. case tuesday:
16. printf("Today is tuesday");
17. break;
18. case wednesday:
19. printf("Today is wednesday");
20. break;
21. case thursday:
22. printf("Today is thursday");
23. break;
24. case friday:
25. printf("Today is friday");
26. break;
27. case saturday:
28. printf("Today is saturday");
29. break;
30. }
31.
32. return 0;
33. }
Output

Some important points related to enum


 The enum names available in an enum type can have the same
value. Let's look at the example.
1. #include <stdio.h>
2.
3. int main(void) {
4. enum fruits{mango = 1, strawberry=0, apple=1};
5. printf("The value of mango is %d", mango);
6. printf("\nThe value of apple is %d", apple);
7. return 0;
8. }
Output

 If we do not provide any value to the enum names, then the


compiler will automatically assign the default values to the
enum names starting from 0.
 We can also provide the values to the enum name in any order,
and the unassigned names will get the default value as the
previous one plus one.
 The values assigned to the enum names must be integral
constant, i.e., it should not be of other types such string, float,
etc.
 All the enum names must be unique in their scope, i.e., if we
define two enum having same scope, then these two enums
should have different enum names otherwise compiler will
throw an error.
Let's understand this scenario through an example.
1. #include <stdio.h>
2. enum status{success, fail};
3. enum boolen{fail,pass};
4. int main(void) {
5.
6. printf("The value of success is %d", success);
7. return 0;
8. }
Output

 In enumeration, we can define an enumerated data type


without the name also.
1. #include <stdio.h>
2. enum {success, fail} status;
3. int main(void) {
4. status=success;
5. printf("The value of status is %d", status);
6. return 0;
7. }
Output

You might also like