Sunteți pe pagina 1din 17

C Day - 2

Topics Covered
1. Pointers
2. Structures
3. Unions
1.0 Introduction to Pointers
Pointers are variables that hold address of another variable of same data type. It is also known
as locator or indicator that points to an address of a value.
Advantage of pointer

Pointers are more efficient in handling Array and Structure.

We can return multiple values from function using pointer.

Pointer allows references to function and thereby helps in passing of function as


arguments to other function.

It reduces length and the program execution time.

It allows C to support dynamic memory management.

Symbols used in pointer


Symbol

Name

Description

& (ampersand sign)

address of operator

determines the address of a variable.

* (asterisk sign)

indirection operator

accesses the value at the address.

Concept of Pointer
Whenever a variable is declared, system will allocate a location to that variable in the memory,
to hold value. This location will have its own address number. Let us assume that system has
allocated memory location fff4 for a variable number
int number = 50 ;
We can access the value 50 by either using the variable name number or the address fff4. Since
the memory addresses are simply numbers they can be assigned to some other variable. The
variable that holds memory address is called pointer variables. Simply a pointer variable holds
an address, which is a location of another variable. Value of that pointer variable will be stored
in another memory location.
Pointer example
As you can see in the figure, pointer variable
stores the address of number variable i.e.
fff4. The value of number variable is 50. But
the address of pointer variable p is aaa3.

Declaring a pointer variable


General syntax of pointer declaration is,
data-type *pointer_name;
Data type of pointer must be same as the variable, which the pointer is pointing. void type
pointer works with all data types, but isn't used oftenly.
Initialization of Pointer variable
Pointer Initialization is the process of assigning address of a variable to pointer variable. In C
language address operator & is used to determine the address of a variable. The

&

(immediately preceding a variable name) returns the address of the variable associated with it.

Dereferencing of Pointer
Once a pointer has been assigned the address of a variable. To access the value of variable,
pointer is dereferenced, using the indirection operator *.

NULL Pointer
A pointer that is not assigned any value but NULL is known as NULL pointer. If you don't have
any address to be specified in the pointer at the time of declaration, you can assign NULL value.
It will a better approach.
int *p=NULL;
Note: In most the libraries, the value of pointer is 0 (zero).

C Pointer to Pointer
In C pointer to pointer means, a pointer refers to the address of another pointer which points to
the address of a value. Let's understand it by the diagram given below:

Let's see the syntax of pointer to pointer.


int **p2;
C pointer to pointer example
Let's see an example where one pointer points to the address of another pointer.

As you can see in the above figure, p2 contains the address of p (fff2) and p contains the
address of number variable (fff4).
#include <stdio.h>
#include <conio.h>
void main()
{
int number=50;
int *p;//pointer to int
int **p2;//pointer to pointer
clrscr();
p=&number;//stores the address of number variable
p2=&p;
printf("Address of number variable is %x \n",&number);
printf("Address of p variable is %x \n",p);
printf("Value of *p variable is %d \n",*p);
printf("Address of p2 variable is %x \n",p2);
printf("Value of **p2 variable is %d \n",**p);
getch();
}
Output
Address of number variable is fff4
Address of p variable is fff4
Value of *p variable is 50
Address of p2 variable is fff2
Value of **p variable is 50

Pointer Arithmetic in C
In C pointer holds address of a value, so there can be arithmetic operations on the pointer
variable. Following arithmetic operations are possible on pointer in C language:

Addition

Subtraction

C Pointer Addition
We can add a value to the pointer variable. The formula of adding value to pointer is given
below:
new_address= current_address + (number * size_of(data type))
Let's see the example of adding value to pointer variable.
#include <stdio.h>
void main(){
int number=50;
int *p;//pointer to int
p=&number;//stores the address of number variable
printf("Address of p variable is %u \n",p);
p=p+3;

//adding 3 to pointer variable

printf("After adding 3: Address of p variable is %u \n",p);


}
Output
Address of p variable is 3214864300
After adding 3: Address of p variable is 3214864312
As you can see, address of p is 3214864300. But after adding 3 with p variable, it is
3214864312 i.e. 4*3=12 increment. Since we are using 64 bit OS, it increments 12. But if we
were using 32 bit OS, it were incrementing to 6 only i.e. 2*3=6. As integer value occupies 2
byte memory in 32 bit OS.
C Pointer Subtraction
Like pointer addition, we can subtract a value from the pointer variable. The formula of
subtracting value from pointer variable is given below:
new_address= current_address - (number * size_of(data type))
Let's see the example of subtract value to pointer variable.
#include <stdio.h>
void main(){
int number=50;
int *p;//pointer to int
p=&number;//stores the address of number variable
printf("Address of p variable is %u \n",p);
p=p-3; //subtracting 3 from pointer variable
printf("After subtracting 3: Address of p variable is %u \n",p);
}

Output
Address of p variable is 3214864300
After subtracting 3: Address of p variable is 3214864288
You can see after subtracting 3 from pointer variable, it is 12 (4*3) less than the previous
address value.

1.1 Pointer and Arrays


When an array is declared, compiler allocates sufficient amount of memory to contain all the
elements of the array. Base address which gives location of the first element is also allocated by
the compiler. Suppose we declare an array arr
int arr[5]={ 1, 2, 3, 4, 5 };
Assuming that the base address of arr is 1000 and each integer requires two byte, the five
elements will be stored as follows

Here variable arr will give the base address, which is a constant pointer pointing to the
element, arr[0]. Therefore arr is containing the address of arr[0] i.e 1000.
arr is equal to &arr[0] // by default
We can declare a pointer of type int to point to the array arr

Now we can access every element of array arr using p++ to move from one element to
another.
Pointer to Array
As studied above, we can use a pointer to point to an Array, and then we can use that pointer
to access the array. Lets have an example,

In the above program, the pointer *p will print all the values stored in the array one by one.

Pointer to Multidimensional Array


A multidimensional array is of form, a[i][j]. Lets see how we can make a pointer point to such
an array. As we know, the name of array gives its base address. In a[i][j], a will give the
base address of this array, that is the address of a[0][0] element.
Here is the generalized form for using pointer with multidimensional arrays.
*(*(ptr + i) + j) is same as a[i][j]
Pointer and Character strings
Pointer can also be used to create strings. Pointer variables of char type are treated as string.
char *str = "Hello";
This creates a string and stores its address in the pointer variable str. The pointer str now
points to the first character of the string "Hello". The content of the string can be printed using
printf() and puts().
printf("%s", str);
puts(str);
Notice that str is pointer to the string, it is also name of the string. Therefore we do not need to
use indirection operator *
Array of Pointers
We can also have array of pointers. Pointers are very helpful in handling character array with
rows of varying length.
char *name[3]={ "Adam", "chris", "Deniel" };
//Now see same array without using pointer
char name[3][20]= "Adam", "chris", "Deniel" };

In the second approach memory wastage is more, hence it is preferred to use pointer in such
cases.

1.2 Pointers and Functions - Call by Reference


When, argument is passed using pointer, address of the memory location is passed instead
of value, it is called call by reference.

Program to swap two number using call by reference.


#include <stdio.h>
void swap(int *a,int *b);
int main(){
int num1=5,num2=10;
swap(&num1,&num2); /* address of num1 and num2 is passed to swap function */
printf("Number1 = %d and Number2 = %d",num1,num2);
return 0;
}
void swap(int *a,int *b){ //pointer a & b points to address of num1 & num2 respectively
int temp;
temp=*a;
*a=*b;
*b=temp;
}
Output
Number1 = 10 and Number2 = 5
Explanation
The

address

of

memory

pointers *a and *baccept

location num1 and num2 are


those

values.

So,

the

passed

to

function

pointer a and b points

and

to

the

address

of num1 and num2 respectively. When, the value of pointer are changed, the value in
memory location also changed correspondingly. Hence, change made to *a and *b was
reflected in num1 and num2 in main function.

1.3 Dynamic memory allocation in C


The concept of dynamic memory allocation in c language allows the C programmer to
allocate memory at runtime.
1. malloc()
2. calloc()
3. realloc()
4. free()
Before learning above functions, let's understand the difference between static memory
allocation and dynamic memory allocation.
static memory allocation

dynamic memory allocation

memory is allocated at compile time.

memory is allocated at run time.

memory can't be increased while executing program.

memory can be increased while executing program.

used in array.

used in linked list.

Now let's have a quick look at the methods used for dynamic memory allocation.
malloc()

allocates single block of requested memory.

calloc()

allocates multiple block of requested memory.

realloc()

reallocates the memory occupied by malloc() or calloc() functions.

free()

frees the dynamically allocated memory.

malloc() function in C

The malloc() function allocates single block of requested memory.

It doesn't initialize memory at execution time, so it has garbage value initially.

It returns NULL if memory is not sufficient.

The syntax of malloc() function is given below:


ptr=(cast-type*)malloc(byte-size)
Let's see the example of malloc() function.
#include <stdio.h>
#include <stdlib.h>
void main(){
int n,i,*ptr,sum=0;
printf("Enter number of elements: ");
scanf("%d",&n);
ptr=(int*)malloc(n*sizeof(int)); //memory allocated using calloc
if(ptr==NULL) {
printf("Sorry! unable to allocate memory");
exit(0);
}
printf("Enter elements of array: ");
for(i=0;i<n;++i) {
scanf("%d",ptr+i);
sum+=*(ptr+i);
}
printf("Sum=%d",sum);
}
Output:
Enter elements of array: 3
Enter elements of array: 10 10 10
Sum=30
calloc() function in C

The calloc() function allocates multiple block of requested memory.

It initially initialize all bytes to zero.

It returns NULL if memory is not sufficient.

The syntax of calloc() function is given below:


ptr=(cast-type*)calloc(number, byte-size)
Let's see the example of calloc() function.
#include <stdio.h>
#include <stdlib.h>
void main(){
int n,i,*ptr,sum=0;
printf("Enter number of elements: ");
scanf("%d",&n);
ptr=(int*)calloc(n,sizeof(int)); //memory allocated using calloc
if(ptr==NULL) {
printf("Sorry! unable to allocate memory");
exit(0);
}

printf("Enter elements of array: ");


for(i=0;i<n;++i) {
scanf("%d",ptr+i);
sum+=*(ptr+i);
}
printf("Sum=%d",sum);
}
Output:
Enter elements of array: 3
Enter elements of array: 10 10 10
Sum=30
realloc() function in C
If memory is not sufficient for malloc() or calloc(), you can reallocate the memory by realloc()
function. In short, it changes the memory size. Let's see the syntax of realloc() function.
ptr=realloc(ptr, new-size)
free() function in C
The memory occupied by malloc() or calloc() functions must be released by calling free()
function. Otherwise, it will consume memory until program exit. Let's see the syntax of free()
function.
free(ptr)

2.0 Introduction to Structure


Structure is a user-defined data type in C which allows you to combine different data types to
store a particular type of record. Structure helps to construct a complex data type in more
meaningful way. Structure is used to represent a record. Suppose you want to store record of
Student which consists of student name, address, roll number and age. You can define a
structure to hold this information.
Defining a structure
struct keyword is used to define a structure. struct define a new data type which is a collection
of different type of data. The genaral syntax as follows:
struct structure_name {
//Statements
}
Example of Structure
struct Book {
char name[15];
int price;
int pages;
};
Here the struct Book declares a structure to hold the details of book which consists of three
data fields, namely name, price and pages. These fields are called structure elements or
members

Declaring Structure Variables


It is possible to declare variables of a structure, after the structure is defined. Structure variable
declaration is similar to the declaration of variables of any other data types. Structure variables
can be declared in following two ways.
Declaring Structure variables separately
struct Student {
char name[20];
int age;
int rollno;
};
struct Student S1 , S2; //declaring variables of Student
Declaring Structure Variables with Structure definition
struct Student [
char name[20];
int age;
int rollno;
}s1, s2;
Here S1 and S2 are variables of structure Student. However this approach is not much
recommended.
Accessing Structure Members
Structure members can be accessed and assigned values in number of ways. Structure member
has no meaning independently. In order to assign a value to a structure member, the member
name must be linked with the structure variable using dot . operator also called period or
member access operator.
struct Book {
char name[15];
int price;
int pages;
}b1, b2;
b1.price = 200

//b1 is variable of Book type and price is member of Book.

We can also use scanf() to give values to structure members through terminal.
scanf(" %s ", b1.name);
scanf(" %d ", &b1.price);
Structure Initialization
Like any other data type, structure variable can also be initialized at compile time.
Struct Book b3 = {c++,200,100}; or //initialization
Struct Book b4;

b4.name = java;
b4.price = 250;
b4.pages = 170;
Keyword typedef while using structure
typedef is a keyword used in C language to assign alternative names to existing types. Its
mostly used with user defined data types, when names of data types get slightly complicated.
Following is the general syntax for using typedef,
typedef existing_name alias_name
Lets take an example and see how typedef actually works.
typedef struct complex{
int imag;
float real;
}comp;
Inside main you can define as:
comp c1,c2;
Here, typedef keyword is used in creating a type comp(which is of type as struct
complex). Then, two structure variables c1 and c2 are created by this comp type.

2.1 Nested Structure in C


Nested structure in c language can have another structure as a member. There are two
ways to define nested structure in c language:
1. By separate structure
2. By Embedded structure
1) Separate structure
We can create 2 structures, but dependent structure should be used inside the main structure
as a member. Let's see the code of nested structure.
struct Date {
int dd;
int mm;
int yyyy;
};
struct Employee {
int id;
char name[20];
struct Date doj;
} emp1;
As you can see, doj (date of joining) is the variable of type Date. Here doj is used as a member
in Employee structure. In this way, we can use Date structure in many structures.

2) Embedded structure
We can define structure within the structure also. It requires less code than previous way. But it
can't be used in many structures.
struct Employee {
int id;
char name[20];
struct Date {
int dd;
int mm;
int yyyy;
}doj;
}emp1;
Accessing Nested Structure
We can access the member of nested structure by Outer_Structure.Nested_Structure.member
as given below:
e1.doj.dd
e1.doj.mm
e1.doj.yyyy
C Nested Structure example
Let's see a simple example of nested structure in C language.
#include <stdio.h>
#include <string.h>
struct Employee {
int id;
char name[20];
struct Date {
int dd;
int mm;
int yyyy;
}doj;
}e1;
void main( ) {
e1.id=101;
//storing employee information
strcpy(e1.name, "Sonoo Jaiswal"); //copying string into char array
e1.doj.dd=10;
e1.doj.mm=11;
e1.doj.yyyy=2014;
printf( "employee id : %d\n", e1.id); //printing employee information
printf( "employee name : %s\n", e1.name);
printf( "employee date of joining (dd/mm/yyyy):%d/%d/%d\n", e1.doj.dd,e1.doj.mm,e1.
doj.yyyy);
}
Output:
employee id : 101
employee name : Sonoo Jaiswal
employee date of joining (dd/mm/yyyy) : 10/11/2014

2.2 Array of Structure


We can also declare an array of structure. Each element of the array representing a structure
variable. Example : struct employee emp[5];
Now we can create a structure(student) which contains name, roll and marks as its data
member. Then, an array of structure of 10 elements is created. Then, data(name, roll and
marks) for 10 elements is asked to user and stored in array of structu re. Finally, the data
entered by user is displayed.
Source Code to Store Information of 10 students Using Structure
#include <stdio.h>
struct student{
char name[50];
int roll;
float marks;
};
void main(){
struct student s[10];
int i;
printf("Enter information of students:\n");
for(i=0;i<10;++i){
s[i].roll=i+1;
printf("\nFor roll number %d\n",s[i].roll);
printf("Enter name: ");
scanf("%s",s[i].name);
printf("Enter marks: ");
scanf("%f",&s[i].marks);
printf("\n");
}
printf("Displaying information of students:\n\n");
for(i=0;i<10;++i) {
printf("\nInformation for roll number %d:\n", s[i].roll);
printf("Name: %s \n Marks: %.1f ", s[i].name("",s[i].marks);
}
}
Output
Enter information of students:
For roll number 1
Enter name: Tom
Enter marks: 98
For roll number 2
Enter name: Jerry
Enter marks: 89
.
.
.

Displaying information of students:


Information for roll number 1:
Name: Tom
Marks: 98
.
.
.

2.3 Structure as function arguments


We can pass a structure as a function argument in similar way as we pass any other variable or
array. In C, structure can be passed to functions by two methods:
1. Passing by value (passing actual value as argument)
2. Passing by reference (passing address of an argument)
Passing structure by value
A structure variable can be passed to the function as an argument as normal variable. If
structure is passed by value, change made in structure variable in function definition does
not reflect in original structure variable in calling function.
Write a C program to create a structure student and take detalis of student in main
function. Pass this structure to a function and display the information in that function.
#include <stdio.h>
struct student{
char name[50];
int roll;
};
void Display(struct student stu);
int main(){
struct student s1;
printf("Enter student's name: ");
scanf("%s",&s1.name);
printf("Enter roll number:");
scanf("%d",&s1.roll);
Display(s1); // passing structure variable s1 as argument
return 0;
}
void Display(struct student stu){
printf("Output\nName: %s",stu.name);
printf("\nRoll: %d",stu.roll);
}
Output
Enter student's name: Kevin Amla
Enter roll number: 149
Output
Name: Kevin Amla
Roll: 149

Passing structure by reference


The address location of structure variable is passed to function while passing it by
reference. If structure is passed by reference, change made in structure variable in
function definition reflects in original structure variable in the calling function.
Write a C program to add two distances(feet-inch system) entered by user.
#include <stdio.h>
struct distance{
int feet;
float inch;
};
void Add(struct distance d1,struct distance d2, struct distance *d3);
void main() {
struct distance dist1, dist2, dist3;
printf("First distance\n");
printf("Enter feet: ");
scanf("%d",&dist1.feet);
printf("Enter inch: ");
scanf("%f",&dist1.inch);
printf("Second distance\n");
printf("Enter feet: ");
scanf("%d",&dist2.feet);
printf("Enter inch: ");
scanf("%f",&dist2.inch);
Add(dist1, dist2, &dist3); /*passing structure variables dist1 and dist2 by value
whereas passing structure variable dist3 by reference */
printf("\nSum of distances = %d\'-%.1f\"",dist3.feet, dist3.inch);
}
void Add(struct distance d1,struct distance d2, struct distance *d3)
{ /* Adding distances d1 and d2 and storing it in d3 */
d3->feet=d1.feet+d2.feet;
d3->inch=d1.inch+d2.inch;
if (d3->inch>=12) {
/* if inch is greater or equal to 12, converting it to feet. */
d3->inch-=12;
++d3->feet;
}
}
Output
First distance
Enter feet: 12
Enter inch: 6.8
Second distance
Enter feet: 5
Enter inch: 7.5
Sum of distances = 18'-2.3"
Explaination: In this program, structure variables dist1 and dist2 are passed by value
and dist3 is passed by reference ,i.e, address of dist3 (&dist3) is passed as an argument.
Thus, the structure pointer variable d3 points to the address of dist3. If any change is
made in d3 variable, effect of it is seed in dist3 variable in main function.

3.0 Unions
Unions are conceptually similar to structures. The syntax of union is also similar to that of
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 same time. A union is declared using union keyword.
union employee {
int id;
char name[20];
float salary;
}emp;
This declares a variable emp 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 a union variable, irrespective of its size. The compiler allocates
the storage that is large enough to hold largest variable type in the union. In the union declared
above the member name requires 20 bytes which is largest among the members. Other
members of union will share the same address.
Advantage of union over structure
It occupies less memory because it occupies the memory of largest member only.
Disadvantage of union over structure
It can store data in one member only.

C Union example
#include <stdio.h>
#include <string.h>
union employee
{

int id;
char name[20];

}e1; //declaring e1 variable for union


int main( ) {
//store first employee information
e1.id=101;
strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array
//printing first employee information
printf( "employee 1 id : %d\n", e1.id);
printf( "employee 1 name : %s\n", e1.name);
return 0;
}
Output:
employee 1 id : 1869508435
employee 1 name : Sonoo Jaiswal
As you can see, id gets garbage value because name has large memory size. So only name will
have actual value.

S-ar putea să vă placă și