Você está na página 1de 18

Unit IV

Pointers

A pointer is a variable whose value is the address of another variable, i.e., direct address of the memory
location.

Declaration
data-type *pointer_name;

Example
int *p;

Benefit of using pointers


 Pointers are more efficient in handling Array and Structure.
 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.

Initialization of Pointer variable


Pointer Initialization is the process of assigning address of a variable to pointer variable. Pointer variable
contains address of variable of same data type. 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.
For example,
int a = 10 ;
int *ptr ; //pointer declaration
ptr = &a ; //pointer initialization
or,
int *ptr = &a ; //initialization and declaration together

Program
#include <stdio.h>
void main ()
{
int var = 20;
int *ip;
ip = &var;
printf("%u\n %u \n %d", &var, ip, *ip );
}
Output
2024
2024
20

NULL Pointers
A pointer that is assigned NULL is called a null pointer.
1
Program
#include <stdio.h>
void main ()
{
int *ptr = NULL;
printf(" %u", ptr );
}
Output
0

Pointer Arithmetic

C pointer is an address, which is a numeric value. There are four arithmetic operators that can be used on
pointers: ++, --, +, and –

Program1
//Program for arithmetic operation
#include <stdio.h>
void main ()
{
int a = 5 , b = 8, *p, *q ;
p = &a;
q = &b;
printf(“%d \t %d \t %d \t %d”, *p+2, *p-1, *p**q, *q/2);
}
Output
7 4 40 4

Program2
//Program for increment operator
#include <stdio.h>
void main ()
{
int var[3] = {10, 100, 200};
int i, *ptr;
ptr = var;
for ( i = 0; i < 3; i++)
{
printf("Address of var[%d] = %u\n", i, ptr );
printf("Value of var[%d] = %d\n", i, *ptr );
ptr++;
}
}

Output
Address of var[0] = 2046
Value of var[0] = 10
Address of var[1] = 2048
Value of var[1] = 100
2
Address of var[2] = 2050
Value of var[2] = 200

Pointers 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 element 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.
int *p;
p = arr; or p = &arr[0]; //both the statements are equivalent.
Now we can access every element of array arr using p++ to move from one element to another.

Program
#include<stdio.h>
void main()
{
int i;
int a[5] = {1, 2, 3, 4, 5};
int *p = a;
for (i=0; i<5; i++)
{
printf("%d", *p);
p++;
}
}

Output
1
2
3
4
5

3
Pointer to Pointer

A pointer to a pointer is a form of multiple indirection, or a chain of pointers. Normally, a pointer contains
the address of a variable. When we define a pointer to a pointer, the first pointer contains the address of the
second pointer, which points to the location that contains the actual value as shown below.

A variable that is a pointer to a pointer must be declared as such. This is done by placing an additional
asterisk in front of its name.
For example, following is the declaration to declare a pointer to a pointer of type int:
int **var;

Program
#include <stdio.h>
void main ()
{
int var = 3000, *ptr, **pptr;
ptr = &var;
pptr = &ptr;
printf("Value of var = %d\n", var );
printf("Value available at *ptr = %d\n", *ptr );
printf("Value available at **pptr = %d\n", **pptr);
}
Output
Value of var = 3000
Value available at *ptr = 3000
Value available at **pptr = 3000

Pointers to Functions

Pointer in function parameter list is used to hold address of argument passed during function call. This is
also known as call by reference. When a function is called by reference any change made to the reference
variable will effect the original variable.

Program
/* C Program to swap two numbers using pointers and function. */
#include <stdio.h>
void swap(int *, int *); // function declaration
void main ()
{
int a = 100, b=200;
printf("Before swap, value of a : %d\n", a );
printf("Before swap, value of b : %d\n", b );
swap(&a, &b); //Function Call
printf("After swap, value of a : %d\n", a );
4
printf("After swap, value of b : %d\n", b );
}
void swap(int *x, int *y) //function definition
{
int temp;
temp = *x;
*x = *y;
*y = temp;
}
Output
Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :200
After swap, value of b :100

Unit – V

Structure

 The structure is a derived data type used to represent heterogeneous data.


 A structure is an aggregation of components that can be treated as a single variable. The components
are called members.

Declaration
Structures are defined via a template and declared with a tag which helps to avoid repeating the definition.
struct keyword is used to define structures.
Syntax
struct structure_name
{
datatype variable-name, variable-name,........;
datatype variable-name, variable-name,........;
datatype variable-name, variable-name,........;
:
:
datatype variable-name, variable-name,........;
};
Example:
struct student
{
int rollno;
char gender;
float marks;
} s1;

Memory Allocation
For the above declaration,

5
Initialization
 Structure variables can be initialized at the time of declaration
 If the structure variable is declared before the main function, the member variables are automatically
initialized to zero or Null.
 If it is partially initialized, then un initialized members will be assigned zero or Null character.
Example
struct Patient
{
float height;
int weight;
int age;
};
struct Patient p1 = { 180.75 , 73, 23 }; //initialization
or
struct Patient p1;
p1.height = 180.75; //initialization of each member separately
p1.weight = 73;
p1.age = 23;

Accessing the Members


Members of the structure can be accessed by using the member access operator “.”(dot)
Syntax:
struct_vble.member-field-name
Example:
◦ emp1.code
◦ emp1.name

//Program to find the size of structure


#include<stdio.h>
struct book
{
char bname[30];
int ssn;
int pages;
}b1;
void main()
{
printf("\nSize of Structure : %d",sizeof(b1));
}
6
Output
Size of Structure : 34

//Program for structure


#include <stdio.h>
struct student
{
char name[50];
int roll;
float marks;
};
int main()
{
struct student s;
printf("Enter name: ");
scanf("%s",s.name);
printf("Enter roll number: ");
scanf("%d",&s.roll);
printf("Enter marks: ");
scanf("%f",&s.marks);
printf("\nDisplaying Information\n");
printf("Name: %s\n",s.name);
printf("Roll: %d\n",s.roll);
printf("Marks: %.2f\n",s.marks);
return 0;
}
Output
Enter information of students:
Enter name: balu
Enter roll number: 25
Enter marks: 87
Displaying Information
Name: balu
Roll: 25
Marks: 87.00

Array of Structure

Structure is used to store the information of One particular object but if we need to store such 100 objects
then Array of Structure is used.

Example
struct Bookinfo
{
char bname[20];
int pages;
int price;
} Book[100];

7
//Program to generate employee details using structure
#include<stdio.h>
#include<conio.h>
struct emp
{
int empno ;
char name[10] ;
int bpay, allow, ded, npay ;
} e[10] ;
void main()
{
int i, n ;
clrscr() ;
printf("Enter the number of employees : ") ;
scanf("%d", &n) ;
for(i = 0 ; i < n ; i++)
{
printf("\nEnter the employee number : ") ;
scanf("%d", &e[i].empno) ;
printf("\nEnter the name : ") ;
scanf("%s", e[i].name) ;
printf("\nEnter the basic pay, allowances & deductions : ") ;
scanf("%d %d %d", &e[i].bpay, &e[i].allow, &e[i].ded) ;
e[i].npay = e[i].bpay + e[i].allow - e[i].ded ;
}
printf("\nEmp. No. Name \t Bpay \t Allow \t Ded \t Npay \n\n") ;
for(i = 0 ; i < n ; i++)
{
printf("%d \t %s \t %d \t %d \t %d \t %d \n", e[i].empno, e[i].name, e[i].bpay,
e[i].allow, e[i].ded, e[i].npay) ;
}
getch() ;
}
Output:
Enter the number of employees : 2
Enter the employee number : 101
Enter the name : Arun
Enter the basic pay, allowances & deductions : 5000 1000 250
Enter the employee number : 102
Enter the name : Babu
Enter the basic pay, allowances & deductions : 7000 1500 750
Emp.No. Name Bpay Allow Ded Npay
101 Arun 5000 1000 250 5750
102 Babu 7000 1500 750 7750

//Program to generate student mark details using structure


#include<stdio.h>
#include<conio.h>
struct student
8
{
int rollno;
char name[20];
int m1,m2,m3;
float percent;
};
void main()
{
struct student s[20],t;
int i,j,n;
clrscr();
printf("\n Enter the no of students:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\n Enter the roll no:");
scanf("%d",&s[i].rollno);
printf("\n Enter the name:");
scanf("%s",s[i].name);
printf("\n Enter the mark1:");
scanf("%d",&s[i].m1);
printf("\n Enter the mark2:");
scanf("%d",&s[i].m2);
printf("\n Enter the mark3:");
scanf("%d",&s[i].m3);
s[i].percent=(s[i].m1+s[i].m2+s[i].m3)/3;
}
printf("\n Student Details \n");
for(i=0;i<n;i++)
{
printf("\n rollno=%d",s[i].rollno);
printf("\t name=%s",s[i].name);
printf("\t mark1=%d",s[i].m1);
printf("\t mark2=%d",s[i].m2);
printf("\t mark3=%d",s[i].m3);
printf("\t percent=%f",s[i].percent);
}
getch();
}
Output
Enter the no of students: 2
Enter the roll no: 12
Enter the name: viji
Enter the mark1: 78
Enter the mark2: 88
Enter the mark3: 67
Enter the roll no: 23
Enter the name: anand
Enter the mark1: 65
9
Enter the mark2: 47
Enter the mark3: 62
Student Details
rollno=12 name=viji mark1=78 mark2=88 mark3=67 percent=77.000000
rollno=23 name=anand mark1=65 mark2=47 mark3=62 percent=58.000000

Structures with Functions

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.

//Program for structures in functions


#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: vijay
Enter roll number:23
Output
Name: vijay
Roll: 23

Nested Structures

Structures can contain members that themselves are structures.

10
Syntax
struct date
{
int day;
int month;
int year;
};
struct employee
{
int code;
char name [20];
struct date doj ;
int dept_code;
float salary;
} emp1,emp2;

Program
#include <stdio.h>
struct Employee
{
char ename[20];
I nt ssn;
float salary;
struct date
{
int date;
int month;
int year;
}doj;
}emp = {"Pritesh",1000,1000.50,{22,6,1990}};
void main()
{
printf("\nEmployee Name : %s",emp.ename);
printf("\nEmployee SSN : %d",emp.ssn);
printf("\nEmployee Salary : %f",emp.salary);
printf("\nEmployee DOJ : %d/%d/%d", emp.doj.date, emp.doj.month, emp.doj.year);
}

Structures with Pointers

Pointers can be accessed along with structures. A pointer variable of structure can be created as below:
struct name
{
member1;
member2;
.
.
};
11
-------- Inside function -------
struct name *ptr;

Here, the pointer variable of type struct name is created.


Structure's member through pointer can be used in two ways:
1. Referencing pointer to another address to access memory
2. Using dynamic memory allocation

//Program for structures with pointers


#include <stdio.h>
struct name
{
int a;
float b;
};
int main()
{
struct name *ptr,p;
ptr=&p;
printf("Enter integer: ");
scanf("%d",&(*ptr).a);
printf("Enter number: ");
scanf("%f",&(*ptr).b);
printf("Displaying: ");
printf("%d%f",(*ptr).a,(*ptr).b);
return 0;
}
Output
Enter integer: 12
Enter number 34.56
Displaying: 12 34.560000

Union

A union is a special data type available in C that enables you to store different data types in the same
memory location.
Declaration
Unions are defined via a template and declared with a tag which helps to avoid repeating the definition.
union keyword is used to define union.
Syntax
union union_name
{
datatype variable-name, variable-name,........;
datatype variable-name, variable-name,........;
datatype variable-name, variable-name,........;
:
:
datatype variable-name, variable-name,........;
};
12
Example:
union student
{
int rollno;
char gender;
float marks;
} s1;

Memory Allocation
For the above declaration,

Initialization
 Union variables can be initialized at the time of declaration
 If the union variable is declared before the main function, the member variables are automatically
initialized to zero or Null.
 If it is partially initialized, then un initialized members will be assigned zero or Null character.
Example
union Patient
{
float height;
int weight;
int age;
};
union Patient p1 = { 180.75 , 73, 23 }; //initialization
or
uniont Patient p1;
p1.height = 180.75; //initialization of each member separately
p1.weight = 73;
p1.age = 23;

Accessing the Members


Members of the union can be accessed by using the member access operator “.”(dot)
Syntax:
union_vble.member-field-name
Example:
◦ emp1.code

//Program to find the size of union


#include<stdio.h>
union book
13
{
char bname[30];
int ssn;
int pages;
}b1;
int main()
{
printf("\nSize of Union : %d",sizeof(b1));
return(0);
}
Output
Size of Union : 30

//Program for union


#include <stdio.h>
union student
{
int roll;
float marks;
char name[50];
};
int main()
{
uniont student s;
printf("Enter roll number: ");
scanf("%d",&s.roll);
printf("Enter marks: ");
scanf("%f",&s.marks);
printf("Enter name: ");
scanf("%s",s.name);
printf("\nDisplaying Information\n");
printf("Roll: %d\n Marks: %.2f \n Name: %s",s.roll, s.marks, s.name);
return 0;
}
Output
Enter roll number: 23
Enter marks: 97
Enter name: priya
Displaying Information
Roll: 29296
Marks: 75757889767977045300000000000000000.00000
Name: priya

Memory Allocation
Example:
union student
{
int rollno;
char gender;
14
float marks;
} s1;

Structures VS Union

Structures Union
It allocates memory equal to sum of memory It allocates piece of memory that is Large
allocated to its each individual member. enough to hold the Largest variable of type in
union
struct keyword is used union keyword is used
Each member have their own memory space. One block is used by all the members of union.
structure cannot be implemented in shared Union is the Best environment where memory
memory. is shared.
It has less Ambiguity. Ambiguity is more in union.
All members can be accessed at a time. only one member is accessed at a time.

C - Storage Classes

A storage class defines the scope (visibility) and life time of variables and/or functions within a C Program.
There are following storage classes which can be used in a C Program.
 auto
 register
 static
 extern

(i) auto Storage Class


 The auto storage class is the default storage class for all local variables. Automatic variables are local
to the block in which they are declared.
 Local variables of different functions/blocks may have the same name. It retains its value till the
control remains in that block. If not initialized, their initial value will be unpredictable.
Syntax:
auto data_type variable_name;
Example
auto int a;
Program:
#include<stdio.h>
void main()
{
auto int i=10;
printf(“%d”,i);
}
Output
10

(ii) register Storage Class


 Registers are faster than memory, keeping the frequently accessed variables like a loop control
variable in a register will increase the execution speed.
15
 Register variables are local (visible) to the block in which they declared. It retains its value till the
control remains in that block. If not initialized, the variable is initialized to zero.
Syntax:
register data_type variable_name;
Example:
register int Miles;

(iii) static Storage Class


Static variables are also local (visible) to the block in which the variable is declared. They retain the values
throughout the life of the program. If not initialized in the declaration, it is automatically initialized to zero.
Syntax:
static data_type variable_name;
Example
static int Count;
Program
#include <stdio.h>
void add();
void main()
{
add();
add();
}
void add()
{
static int i=10;
printf(“\n%d”,i);
i=i+1;
}
Output
10
11

(iv) extern Storage Class


External variables are not confined to a single function. Their scope extends from the point of definition
through the remainder of the program. They are referred to as global variables.
Syntax:
extern data_type variable_name;
Example
extern int Count;
Program
#include<stdio.h>
extern int i=10; //extern variable
void display();
void main()
{
int i=2;
printf(“%d”,i);
display();
printf(“%d”,i);
16
}
void display()
{
printf(“\n%d”,i);
i=i+1;
}
Output
2
10
2

C Preprocessors

The C Preprocessor is not part of the compiler, but is a separate step in the compilation process. The
preprocessor provides the ability for the inclusion of header files, macro expansions, conditional
compilation, and line control.
Examples
o unconditional directives : #include, #define, #undef
o conditional directives are: #ifdef, #ifndef, #if, #else, #elif, #endif

1. File Inclusion
The #include directive allows external files to be added in to our source file, and then processed by the
compiler.
Syntax
#include <header file> or
#include “header file”

If the file name is enclosed between angle-brackets <>, the file is searched in the directories where the
compiler is configured to look for the standard header files. In the second case, the file is searched first in
the current working directory.

2. Macro Substitution
 #define preprocessor directive is used to define a macro that assigns a value to an identifier.
 The preprocessor replaces subsequent occurrences of that identifier with its assigned value until the
identifier is undefined with the #undef preprocessor directive.

There are two basic types of macro definitions that can be used to assign a value to an identifier:
 Object-like Macros: Replaces a single identifier with a specified token or constant value.
 Function-like Macros: Associates a user-defined macro function and argument list to an identifier.

(i) Object-Like Macros (Symbolic Constants)


The preprocessing directives #define and #undef allow the definition of identifiers which can hold a certain
value. These identifiers can simply be constants or a macro function.
Syntax
#define <symbolic variable name> value
Example
#define SIZE 10
Program

17
#include <stdio.h>
#define clr 100
void main()
{
printf("%d\n",clr);
}
Output
100

(ii) Function Like Macros


Syntax
#define macro_name (argument list) macro_defn
Example
#define square(a) ((a)*(a))
Program
#include <stdio.h>
#define square(x) x*x
void main()
{
int i;
i = 64/square(4);
printf("%d",i);
}
Output
64

(iii) Conditional Compilation


 A preprocessor conditional compilation directive causes the preprocessor to conditionally suppress
the compilation of portions of source code.
 The conditional directives are:
#ifdef - If this macro is defined
#ifndef - If this macro is not defined
#if - Test if a compile time condition is true
#else - The alternative for #if
#elif - #else an #if in one statement
#endif - End preprocessor conditional
Program
#include <stdio.h>
#define a 1
void main()
{
#ifdef a
printf(“\n a is defined");
#else
printf(“\n a is not defined");
#endif
}
Output
a is defined
18

Você também pode gostar