pointer

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 10

UNIT-IV

A pointer is a variable which stores the memory address of another variable. Pointers are used
to store the address of variables.

Declaring a pointer:
A pointer is a variable that holds the memory address of another variable as its value. The
general form to declare a pointer variable is:
Syntax:
datatype *ptr_var;
Ex: int *ptr;
char *c;
Here ‘ptr’ is a pointer variable that contains address of a variable which is of integer type.
All the data types of pointer variables can hold 2 bytes of memory.

Initializing a pointer:
A pointer variable can be declared first and later assigned a value as shown below:
Syntax: pointer_variable= &variable;
Ex: int a,*p;
a=10;
p=&a;
Example:
#include <stdio.h>
#include <conio.h>
main()
{
int n,*p;
p=&n;
clrscr();
printf("Enter the number:");
scanf("%d",&n);
printf("\n The number that was entered is %d",*p);
printf("\n The address of number in memory is %p",&n);
getch();
}
Output:
Enter the number: 5
The number that was entered is 5
The address of number in memory is FFD0

Note: %p control string prints a memory address in hexadecimal form. %u prints


memory address in decimal form.

POINTER EXPRESSIONS AND POINTER ARITHMETIC


Pointer variable can also be used in expression. An expression is a collection of operands
joined together by certain operator that represent a value. Like other variables, pointer
variables can be used in expressions.

1
UNIT-IV

Ex: 1 Ex: 2
#include <stdio.h> #include<stdio.h>
#include <conio.h> #include<conio.h>
main() main()
{ {
int n1,n2,sum=0,mul=0,*p1,*p2; int a,b,*p1,*p2,x,y,z;
float div; a=12;
p1=&n1; b=4;
p2=&n2; clrscr();
clrscr(); p1=&a;
printf("Enter n1,n2 values:\n"); p2=&b;
scanf("%d%d",&n1,&n2); x=*p1 * *p2 - 6;
sum=*p1+*p2; y=4 * -(*p2) / (*p1) + 10;
mul=*p1**p2; printf("\n addresss of a:%u",p1);
div=(*p1)/(*p2); printf("\n address of b:%u",p2);
printf("\n sum= %d",sum); printf("\n\n a=%d,b=%d",a,b);
printf("\n mul= %d",mul); printf("\n\n x=%d,y=%d",x,y);
printf("\n div= %f",div); *p2=*p2+3;
getch(); *p1=*p2-5;
} z=*p1 * *p2 - 6;
Output: printf("\n a=%d,b=%d",a,b);
Enter n1,n2 values: printf("\n z=%d",z);
25 getch();
4 }
sum= 29 Output:
mul= 100 addresss of a:65482
div= 6.000000 address of b:65484
a=12,b=4
x=42,y=9
a=2,b=7
z=8

Null Pointer: It is a special pointer value that does not point anywhere. This means that a
NULL pointer does not point to any valid memory address.

PASSING ARGUMENTS TO FUNCTION USING POINTERS


#include<stdio.h> printf("\n values after swapping");
#include<conio.h> printf("\n x=%d \t y=%d",x,y);
void swap(int *a,int *b); getch();
void main() }
{ void swap(int *a,int *b)
int x,y; {
clrscr(); int t;
x=10; t=*a; Output:
y=20; *a=*b; Values before swapping
printf("\n values before swapping"); *b=t; x=10 y=20
printf("\n x=%d \t y=%d",x,y); } Values after swapping
swap(&x,&y); x=20 y=10

2
UNIT-IV

POINTERS AND ONE-DIMENSIONAL ARRAYS


When an array is declared, the complier allocates a base address and sufficient memory
storage for the elements. To access the array elements the address of the first element of an
array can be assigned to the pointer variable and using this address we can access the
remaining elements of that array.
For example:
int a[5]={10,20,30,40,50}, *p;
p = a; /* p=&a[0] */
Memory representation is
10 20 30 40 50
a[0] a[1] a[2] a[3] a[4]
65462 65464 65466 65468 65470
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
int a[5]={10,20,30,40,50}; Output:
int i, *p; Given elements are: 10 20 30 40 50
clrscr(); Given elements address are: 65490 65492 65494
p=a; 65496 65498
printf("\n Given elements are:");
for(i=0;i<5;i++)
{
printf("%d\t",*(p+i));
}
printf("\n Given elements address are :");
for(i=0;i<5;i++)
{
printf("%d \t",p+i);
}
getch();
}
Pointers and strings
Strings are treated as arrays of characters that are terminated with null character. C
language provides two alternate ways of declaring and initializing a string. First
char str[10]={‘H’,’E’,’L’,’L’,’O’,’\0’}; or
char str[10]=”HELLO”;
When the double quotes are used null character is automatically appended to the end
of the string.
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
char name[]="HELLO";
char *c;
clrscr();
c=name;
printf("The given string is: ");

3
UNIT-IV

while(*c!='\0')
{
printf("%c",*c);
c++;
} getch(); } Output: The given string is: HELLO
ADVANTAGES AND DISADVANTAGES
Advantages:
1. Pointers reduce the length and complexity of the program.
2. Array elements can be easily accessed.
3. Execution of a program is faster.
4. Pointers are frequently used to pass the information in functions.
5. Arguments passed to function can be modified.
6. Memory can be efficiently used through dynamic memory allocation.
Disadvantages:
1. If sufficient memory is not available during runtime for the storage of pointers, the
program may crash.
2. If the programmer is not careful and consistent with the use of pointers, the program
may crash (very possible).
3. Uninitialized pointers might cause segmentation fault.

STRUCTURES
A structure is a collection of data items of different data types referenced under a
same name.
Syntax: structure declaration:
struct structure-name
{
datatype member1;
datatype member2;
-------------
-------------
};
A structure can be defined by using the keyword ‘struct’. Each individual item of a
structure is called a member (member variable).
Ex:
Struct student
{
int sno;
char sname[10];
int s1,s2;
};
Defining structure variable:
A structure variable can be defined in the main() function, before or after.
Syntax: struct structure-name variable-list;
2 10 2 2

s.sno s.sname s.s1 s.s2

Ex: struct student s; (or)


struct student s1,s2,s3;

4
UNIT-IV

The structure variables are created with separate address location in the memory.

Initializing of structure:
Like simple and array variables, structure type variables can also be initialized while they are
declaring. Initializing a structure means assigning some constants to the members of the
structure.
Syntax:
struct structure-name var1 = { values }, var2 = {values},……., var-n = {values};
Ex:
1) struct student s={a,”raju”,77,88};
2) struct stud s1 = {1,”ABC”, 45,55 }, s2 = {2,”XYZ”,90,89};
Accessing Structure Elements:
Individual members of a structure are accessed through the use of dot (.) operator. This
operator is placed between a structure variable and structure members.
Syntax: structure_variable.member

Ex: printf(“\n sno=%d”,s.sno);


printf(“\n sname=%s”,s.sname);
Program:
/* write a program to find sum and average of student marks using structures
*/
#include<stdio.h>
#include<conio.h>
struct student
{
int sno,s1,s2,tot;
char sname[10];
float avg;
};
main()
{
struct student s;
clrscr();
printf("\n Enter sno,sname,s1,s2:\n");
scanf("%d%s%d%d",&s.sno,s.sname,&s.s1,&s.s2);
s.tot=s.s1+s.s2;
s.avg=s.tot/2.0;
printf("\n total=%d",s.tot);
printf("\n average=%f",s.avg);
getch();
}
ARRAY OF STRUCTURES
To declare an array of structure we must first define a structure and then declare an array of
that type.
Syntax: Structure structure_name array_name [size];
Example: struct student
{
int sno;
char sname[20];

5
UNIT-IV

float avg;
};
struct student s[10];
The above example creates 10 elements of type ‘student’. The conceptual view of the above
declaration is as shown below:

sno sname avg


s[0]
s[1]
s[2]

s[9]

To access an individual element in an array of structures, we use a subscript or index. Like all
array variables, arrays of structures also begin indexing at 0. The individual members are
accessed as follows:
s[0].sno, s[0].sname, s[0].avg,s[1].sno,s[1].sname,s[1].avg………...s[9].avg

Example:
/* program for array of structures */
#include<stdio.h>
#include<conio.h>
struct emp
{
int eno;
char ename[10];
int sal;
};
main()
{
int i;
struct emp e[3]={{1,"ramu",1000},{2,"sita",2000},{3,"Krishna",3000}};
for(i=0;i<3;i++)
{
printf("\n eno=%d",e[i].eno);
printf("\n ename=%s",e[i].ename);
printf("\n salary=%d",e[i].sal);
}
getch();
}
NESTED STRUCTURES
When a structure is an element of another structure, it is called a nested structure.
#include<stdio.h>
#include<conio.h>
struct marks
{
int inter,exter;

6
UNIT-IV

};
struct student
{
int sno;
char sname[10];
struct marks m;
};
main()
{
struct student s;
int tot;
printf("\n Enter sno & sname:\n");
scanf("%d%s",&s.sno,s.sname);
printf("\n Enter internal marks:");
scanf("%d",&s.m.inter);
printf("\n Enter external marks:");
scanf("%d",&s.m.exter);
tot=s.m.inter+s.m.exter;
printf("\n total=%d",tot);
getch();
}
UNIONS
Union is also a collection of data items may be of different types or same data types
referenced under a same name.
The members within the union all share the same storage area within the computer’s memory.
When the union is declared, the compiler automatically allocates memory location to the
largest data type of members in the union.
Declaring a union:
The keyword ‘union’ is used to define a union. The union defines the follows:
Syntax:
union union_name
{
datatype member1;
datatype member 2;
--------------------
datatype member n;
};
union union_name variable-list;
Ex:
union member
{
int a;
flaot b;
char c;
};
Union member m;
In the above example the memory will be allocated the highest memory location i.e. 4bytes
will be allocated.

Accessing Union Members:

7
UNIT-IV

We can access the individual members of a union through the use of a dot operator. The
general format is as follows:
Ex:- m.a, m.b, …………
Ex:
#include<stdio.h>
union point
{
int x,y;
};
main()
{
union point p;
p.x=3;
p.y=5;
clrscr();
printf("\n The coordinates of P are %d and %d",p.x, p.y);
getch();
}
DIFFERENCE BETWEEN STRUCTURE AND UNION

Structure Unions
1. structure is a collection of data 1. Union is a collection of data item
item may of different data types may of different data types
referenced under one name referenced under one name
2. Structure is defined by ‘struct’ 2. The Union is defined by ‘union’
keyword as keyword as
Struct tag union tag
{ {
datatype memeber1; datatype memeber1;
datatype memeber2; datatype memeber2;
------------------------ ------------------------
datatype member-n; datatype member-n;
}var1,var2,…..var-n }var1,var2,…..var-n;
3. In a structure, memory is reserved
for all members of that structure 3. In a union, memory is reserved
4. All members of structure cannot only for the largest member of
share the same storage area that union
5. We can store data for all members 4. All members of structure can
in the structure share the same storage area
6. We can store data for all members 5. All members of union cannot be
in the structure accessed at a time
7. The structure variable can be 6. We can store data for only one
initialized and can give values for member of an union
al members. 7. The union variables cannot be
Ex: initialized. But if we want to
Struct temp m={10,50.25,’M’}; initialize, we can give value to the
first member only
Ex:
Union temp m={10};

8
UNIT-IV

DYNAMIC MEMORY ALLOCATION


The process of allocating memory at runtime is known as Dynamic Memory Allocation or
Runtime Memory Allocation. There are four library functions to allocate and freeing memory
during the program execution.
1. Malloc(): Allocates requested size of bytes and returns a pointer to the first byte of
the allocated space.
Syntax:
pv = (type *) malloc (size);
2. Calloc(): Allocates space for an array of elements, initializes from 0 and return a
pointer to the memory.
Syntax:
Pv =(type *)calloc (n, size);

3. Realloc(): it modifies the size of the previously allocated memory space.


Syntax: realloc(pointername, n*sizeof(int));

4. Free(): Free previously allocated memory space.


Syntax: free(filepointer);

Program: #include<stdio.h>
#include<conio.h>
main()
{
int n,i,*p,sum=0;
clrscr(); Output:
printf("Enter number of elements:"); Enter number of elements:0
scanf("%d",&n); Error!Memory not allocated
p=(int*)malloc(n*sizeof(int));
if(p==NULL) Enter number of elements:3
{ Enter 3 elemets
printf("\n Error!Memory not allocated"); 10
exit(0); 25
} 15
printf("\n Enter %d elemets\n",n); The sum of elements=50
for(i=0;i<n;i++)
{
scanf("%d",(p+i));
sum+=*(p+i);
}
printf("\n The sum of elements=%d",sum);
getch();
}

ENUMERATED DATA TYPES


Enumeration types are user-defined types that allows programmer to name a finite set of
elements, which are called enumerators or enumeration constants or enumeration members.
Defining an Enumeration type:

9
UNIT-IV

Syntax: enum tag {id1, id2, id3, …….., id-n};


Here, ‘tag’ is the name of enumeration type and id1, id2, id3,….., id-n are identifiers which
represent enumeration constants. By default, ‘c’ compiler assigns integer values starting from
zero to each identifier automatically. But we can change these values.
Ex:1 enum grade {distinction, first, second, third};
In this example , ‘grade’ is the name of enumeration tag, and ‘distinction, first, second, third’
are the enumeration constants which assigns values 0,1,2,3 respectively.
Ex:2 enum grade {distinction = 10, first=20, second=30, third=40};
In this example enumeration constants are assigned with values 10,20 ,30, and 40
respectively.
Declaring Enumeration variables:
Once enumeration type has been defined, one or more variables of that type can be declared.
The declaration is as follows:
Syntax: enum tag var1, var2, …, var-n;
Every variable of enumeration type occupies only two bytes of memory.
Ex: enum grade g;
Sample program:/* enumeration */
#include<stdio.h>
#include<conio.h>
enum grade{distinction,first,second,third};
main()
{
enum grade g;
printf("%d\n",distinction);
printf("%d\n",third);
getch();
}

10

You might also like