Structure, Union and Pointers
Structure, Union and Pointers
Structure, Union and Pointers
Defining a structure
struct keyword is used to define a structure. struct defines a new data type which is a
collection of primary and derived datatypes.
Syntax:
struct [structure_tag]
{
//member variable 1
//member variable 2
//member variable 3
...
}[structure_variables];
As you can see in the syntax above, we start with the struct keyword, then it's optional
to provide your structure a name, we suggest you to give it a name, then inside the curly
braces, we have to mention all the member variables, which are nothing but normal C
language variables of different types like int, float, array etc.
After the closing curly brace, we can specify one or more structure variables, again this
is optional.
Note: The closing curly brace in the structure type declaration must be followed by a
semicolon(;).
Example of Structure
struct Student
{
char name[25];
int age;
char branch[10];
// F for female and M for male
char gender;
};
Here struct Student declares a structure to hold the details of a student which consists
of 4 data fields, namely name, age, branch and gender. These fields are called structure
elements or members.
Each member can have different datatype, like in this case, name is an array
of char type and age is of int type etc. Student is the name of the structure and is
called as the structure tag
struct Student
{
char name[25];
int age;
char branch[10];
//F for female and M for male
char gender;
};
int main()
{
struct Student s1;
/*
s1 is a variable of Student type and
age is a member of Student
*/
s1.age = 18;
/*
using string function to add name
*/
strcpy(s1.name, "Viraaj");
/*
displaying the stored values
*/
printf("Name of Student 1: %s\n", s1.name);
printf("Age of Student 1: %d\n", s1.age);
return 0;
}
Output:
Name of Student 1: Viraaj
Age of Student 1: 18
We can also use scanf() to give values to structure members through terminal.
scanf(" %s ", s1.name);
scanf(" %d ", &s1.age);
Structure Initialization
Like a variable of any other datatype, structure variable can also be initialized at compile
time.
struct Patient
{
float height;
int weight;
int age;
};
Array of Structure
We can also declare an array of structure variables. in which each element of the array
will represent a structure variable. Example : struct employee emp[5];
The below program defines an array emp of size 5. Each element of the array emp is of
type Employee.
#include<stdio.h>
struct Employee
{
char ename[10];
int sal;
};
Nested Structures
Nesting of structures, is also permitted in C language. Nested structures means, that
one structure has another stucture as member variable.
Example:
struct Student
{
char[30] name;
int age;
/* here Address is a structure */
struct Address
{
char[50] locality;
char[50] city;
int pincode;
}addr;
};
struct Student
{
char name[10];
int roll;
};
void main()
{
struct Student std;
printf("\nEnter Student record:\n");
printf("\nStudent name:\t");
scanf("%s", std.name);
printf("\nEnter Student rollno.:\t");
scanf("%d", &std.roll);
show(std);
}
void show(struct Student st)
{
printf("\nstudent name is %s", st.name);
printf("\nroll is %d", st.roll);
}
The keyword ‘enum’ is used to declare new enumeration types in C and C++. Following
is an example of enum declaration.
Output:
int main()
{
enum week day;
day = Wed;
printf("%d",day);
return 0;
}
In the above example, we declared “day” as the variable and the value of “Wed” is
allocated to day, which is 2. So as a result, 2 is printed.
Another example of enumeration is:
// Another example program to demonstrate working
// of enum in C
#include<stdio.h>
int main()
{
int i;
for (i=Jan; i<=Dec; i++)
printf("%d ", i);
return 0;
}
Output:
0 1 2 3 4 5 6 7 8 9 10 11
In this example, the for loop will run from i = 0 to i = 11, as initially the value of i is Jan
which is 0 and the value of Dec is 11.
typedef in C
typedef is a keyword used in C language to assign alternative names to existing
datatypes. Its mostly used with user defined datatypes, when names of the datatypes
become slightly complicated to use in programs. Following is the general syntax for
using typedef,
typedef <existing_name> <alias_name>
Lets take an example and see how typedef actually works.
typedef unsigned long ulong;
The above statement define a term ulong for an unsigned long datatype. Now
this ulong identifier can be used to define unsigned long type variables.
ulong i, j;
Application of typedef
typedef can be used to give a name to user defined data type as well. Lets see its use
with structures.
typedef struct
{
type member1;
type member2;
type member3;
} type_name;
Here type_name represents the stucture definition associated with it. Now
this type_name can be used to declare a variable of this stucture type.
type_name t1, t2;
C Unions
Unions are conceptually similar to structures. The syntax to declare/define a union is
also similar to that of a structure. The only differences is in terms of storage.
In structure each member has its own storage location, whereas all members
of union uses a single shared memory location which is equal to the size of its largest
data member.
This implies that although a union may contain many members of different types, it
cannot handle all the members at the same time. A union is declared using
the union keyword.
union item
{
int m;
float x;
char c;
}It1;
This declares a variable It1 of type union item. This union contains three members
each with a different data type. However only one of them can be used at a time. This is
due to the fact that only one location is allocated for all the union variables, irrespective
of their size. The compiler allocates the storage that is large enough to hold the largest
variable type in the union.
In the union declared above the member x requires 4 bytes which is largest amongst
the members for a 16-bit machine. Other members of union will share the same
memory address.
#include <stdio.h>
union item
{
int a;
float b;
char ch;
};
int main( )
{
union item it;
it.a = 12;
it.b = 20.2;
it.ch = 'z';
printf("%d\n", it.a);
printf("%f\n", it.b);
printf("%c\n", it.ch);
return 0;
}
Output:
26426
20.1999
z
As you can see here, the values of a and b get corrupted and only variable c prints the
expected result. This is because in union, the memory is shared among different data
types. Hence, the only member whose value is currently stored will have the memory.
In the above example, value of the variable c was stored at last, hence the value of
other variables is lost.
Introduction to C Pointers
A Pointer in C language is a variable which holds the address of another variable of
same data type.
Pointers are used to access memory and manipulate the address.
Pointers are one of the most distinct and exciting features of C language. It provides
power and flexibility to the language. Although pointers may appear a little confusing
and complicated in the beginning, but trust me, once you understand the concept, you
will be able to do so much more with C language.
Before we start understanding what pointers are and what they can do, let's start by
understanding what does "Address of a memory location" means?
Address in C
Whenever a variable is defined in C language, a memory location is assigned for it, in
which it's value will be stored. We can easily check this memory address, using
the & symbol.
If var is the name of the variable, then &var will give it's address.
Let's write a small program to see memory address of any variable that we define in our
program.
#include<stdio.h>
void main()
{
int var = 7;
printf("Value of the variable var is: %d\n", var);
printf("Memory address of the variable var is: %x\n", &var);
}
Concept of Pointers
Whenever a variable is declared in a program, system allocates a location i.e an
address to that variable in the memory, to hold the assigned value. This location has its
own address number, which we just saw above.
Let us assume that system has allocated memory location 80F for a variable a.
int a = 10;
We can access the value 10 either by using the variable name a or by using its
address 80F.
The question is how we can access a variable using it's address? Since the memory
addresses are also just numbers, they can also be assigned to some other variable.
The variables which are used to hold memory addresses are called Pointer variables.
A pointer variable is therefore nothing but a variable which holds an address of some
other variable. And the value of a pointer variable gets stored in another memory
location.
Benefits of using pointers
Below we have listed a few benefits of using pointers:
In the next tutorial we will learn syntax of pointers, how to declare and define a pointer,
and using a pointer. See you in the next tutorial.
void main()
{
int a = 10;
int *ptr; //pointer declaration
ptr = &a; //pointer initialization
}
Pointer variable always point to variables of same datatype. Let's have an example to
showcase this:
#include<stdio.h>
void main()
{
float a;
int *ptr;
ptr = &a; // ERROR, type mismatch
}
If you are not sure about which variable's address to assign to a pointer variable while
declaration, it is recommended to assign a NULL value to your pointer variable. A pointer
which is assigned a NULL value is called a NULL pointer.
#include <stdio.h>
int main()
{
int *ptr = NULL;
return 0;
}
int main()
{
int a, *p; // declaring the variable and pointer
a = 10;
p = &a; // initializing the pointer