0% found this document useful (0 votes)
26 views25 pages

Cs1104 - Unit IV

Uploaded by

frankvenas25
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views25 pages

Cs1104 - Unit IV

Uploaded by

frankvenas25
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

Pointers

Pointer is a variable that stores/hold address of another variable of same data type/ t is also known
as locator or indicator that points to an address of a value. A pointer is a derived data type in C

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.
Declaration of Pointer
data_type* pointer_variable_name; int* p;
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 typeint a = 10 ;

int *ptr ; //pointer declaration

ptr = &a ; //pointer initializationor,

int *ptr = &a ; //initialization and declaration together

Note:Pointer variable always points to same type of data.

float a;

int *ptr;

ptr = &a; //ERROR, type mismatch

Above statement defines, p as pointer variable of type int.


Pointer example
As you can see in the above 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.
By the help of * (indirection operator), we can print the value of pointer variable p.
Reference operator (&) and Dereference operator (*)
& is called reference operator. It gives you the address of a variable. There is another operator that
gets you the value from the address, it is called a dereference operator (*).
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.

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 *.
int a,*p; a = 10;
p = &a;
printf("%d",*p); //this will print the value of a.
printf("%d",*&a); //this will also print the value of a.
printf("%u",&a); //this will print the address of a.
printf("%u",p); //this will also print the address of a.
printf("%u",&p); //this will also print the address of p.
KEY POINTS TO REMEMBER ABOUT POINTERS IN C:
• Normal variable stores the value whereas pointer variable stores the address of the variable.
• The content of the C pointer always be a whole number i.e. address.
• Always C pointer is initialized to null, i.e. int *p = null.
• The value of null pointer is 0.
• & symbol is used to get the address of the variable.
• symbol is used to get the value of the variable that the pointer is pointing to.
• If a pointer in C is assigned to NULL, it means it is pointing to nothing.
• Two pointers can be subtracted to know how many elements are available between these
two pointers.
• But, Pointer addition, multiplication, division are not allowed.
• The size of any pointer is 2 byte (for 16 bit compiler).
Example:

#include <stdio.h>
#include <conio.h>
void main(){
int number=50;
int *p;
clrscr();
p=&number;//stores the address of number variable
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); getch();
}

Output

Address of number variable is fff4


Address of p variable is fff4
Value of p variable is 50
Example:
#include <stdio.h>
int main()
{
int *ptr, q; q = 50;
/* address of q is assigned to ptr */
ptr = &q;
/* display q's value using ptr variable */
printf("%d", *ptr);
return 0;
}
Output
50
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.
Or
It is always a good practice to assign a NULL value to a pointer variable in case you do not have
an exact address to be assigned. This is done at the time of variable declaration. A pointer that is
assigned NULL is called a null pointer.int *p=NULL;
Note: The NULL pointer is a constant with a value of zero defined in several standard libraries/ in
most the libraries, the value of pointer is 0 (zero)
Arrays and Pointers
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 arr[5]={ 1, 2, 3, 4, 5 };
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.
Pointer to Array
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,
int i;
int a[5] = {1, 2, 3, 4, 5};
int *p = a; // same as int*p = &a[0]
for (i=0; i<5; i++)
{
printf("%d", *p); p++;
}

In the above program, the pointer *p will print all the values stored in the array one by one. We
can also use the Base address (a in above case) to act as pointer and print all the values.
Relation between Arrays and Pointers
Consider an array:
int arr[4];

In C programming, name of the array always points to address of the first

element of an array. In the above example, arr and &arr[0] points to the address

of the first element.

&arr[0] is equivalent to arr

Since, the addresses of both are the same, the values of arr and &arr[0] are also the same.

arr[0] is equivalent to *arr (value of an address of the pointer)


Similarly,
&arr[1] is equivalent to (arr + 1) AND, arr[1] is equivalent to *(arr + 1).
&arr[2] is equivalent to (arr + 2) AND, arr[2] is equivalent to *(arr + 2).
&arr[3] is equivalent to (arr + 3) AND, arr[3] is equivalent to *(arr + 3).
.
.
&arr[i] is equivalent to (arr + i) AND, arr[i] is equivalent to *(arr + i).
Example: Program to find the sum of six numbers with arrays and pointers
#include <stdio.h>
int main()
{
int i, classes[6],sum = 0;
printf("Enter 6 numbers:\n");
for(i = 0; i < 6; ++i)
{
scanf("%d",(classes + i));
sum += *(classes + i);
}
printf("Sum = %d", sum); return 0;
}
OUPUT

Enter 6 numbers:

Sum = 21
Pointers to functions/ Function Pointers
• A pointer to a function points to the address of the executable code of the function.
• We can use pointers to call functions and to pass functions as arguments to other functions.
• We cannot perform pointer arithmetic on pointers to functions.
• The type of a pointer to a function is based on both the return type and parameter types of
the function.
• A declaration of a pointer to a function must have the pointer name in parentheses.
• The function call operator () has a higher precedence than the dereference operator *.
Without them, the compiler interprets the statement as a function that returns a pointer to
a specified return type.
declare Pointer to function?

<function return type>(*<Pointer_name>)(function argument list)


For example:
int *f(int a); /* function f returning an int * */
Calling a function through a function pointer
We already know how to call a function in the usual way. Now, we will see how to call a function
using a function pointer.
Suppose we declare a function as given below:
float func(int , int); // Declaration of a function.
Calling an above function using a usual way is given below:
result = func(a , b); // Calling a function using usual ways.
Calling a function using a function pointer is given below:
result = (*fp)( a , b); // Calling a function using function pointer.
Or
result = fp(a , b); // Calling a function using function pointer, and indirection operator
can be removed.

The effect of calling a function by its name or function pointer is the same. If we are using the
function pointer, we can omit the indirection operator as we did in the second case. Still, we use
the indirection operator as it makes it clear to the user that we are using a function pointer.
Example
#include <stdio.h>
int add(int,int);
int main()
{
int a,b;
int (*ip)(int,int);
int result;
printf("Enter the values of a and b : ");
scanf("%d %d",&a,&b);
ip=add;
result=(*ip)(a,b);
printf("Value after addition is : %d",result);
return 0;
}
int add(int a,int b)
{
int c=a+b;
return c;
}
Output

Passing a function's address as an argument to other function


include <stdio.h>
void func1(void (*ptr)());
void func2();
int main()
{
func1(func2);
return 0;
}
void func1(void (*ptr)())
{
printf("Function1 is called");
(*ptr)();
}
void func2()
{
printf("\nFunction2 is called");
}
Output

Array of Function Pointers


Function pointers are used in those applications where we do not know in advance which function
will be called. In an array of function pointers, array takes the addresses of different functions, and
the appropriate function will be called based on the index number.
Let's understand through an example.
#include <stdio.h>
float add(float,int);
float sub(float,int);
float mul(float,int);
float div(float,int);
int main()
{
float x; // variable declaration.
int y;
float (*fp[4]) (float,int); // function pointer declaration.
fp[0]=add; // assigning addresses to the elements of an array of a function pointer.
fp[1]=sub;
fp[2]=mul;
fp[3]=div;
printf("Enter the values of x and y :");
scanf("%f %d",&x,&y);
float r=(*fp[0]) (x,y); // Calling add() function.
printf("\nSum of two values is : %f",r);
r=(*fp[1]) (x,y); // Calling sub() function.
printf("\nDifference of two values is : %f",r);
r=(*fp[2]) (x,y); // Calliung sub() function.
printf("\nMultiplication of two values is : %f",r);
r=(*fp[3]) (x,y); // Calling div() function.
printf("\nDivision of two values is : %f",r);
return 0;
}

float add(float x,int y)


{
float a=x+y;
return a;
}
float sub(float x,int y)
{
float a=x-y;
return a;
}
float mul(float x,int y)
{
float a=x*y;
return a;
}
float div(float x,int y)
{
float a=x/y;
return a;
}
Output

Strings and Pointers


Creating a pointer for the string
The variable name of the string str holds the address of the first element of the array i.e., it points
at the starting memory address.
So, we can create a character pointer ptr and store the address of the string str variable in it. This
way, ptr will point at the string str.
In the following code we are assigning the address of the string str to the pointer ptr.

char *ptr = str;

We can represent the character pointer variable ptr as follows.


The pointer variable ptr is allocated memory address 8000 and it holds the address of the string
variable str i.e., 1000.
Accessing string via pointer
To access and print the elements of the string we can use a loop and check for the \0 null character.
In the following example we are using while loop to print the characters of the string variable str.

#include <stdio.h>
int main(void) {
// string variable
char str[6] = "Hello";
// pointer variable
char *ptr = str;
// print the string
while(*ptr != '\0') {
printf("%c", *ptr);
// move the ptr pointer to the next memory location
ptr++; }
return 0;
}
Using pointer to store string
We can achieve the same result by creating a character pointer that points at a string value stored
at some memory location.
In the following example we are using character pointer variable strPtr to store string value.

#include <stdio.h>
int main(void) {

// pointer variable to store string


char *strPtr = "Hello";
// temporary pointer variable
char *t = strPtr;
// print the string
while(*t != '\0') {
printf("%c", *t);

// move the t pointer to the next memory location


t++;
}
return 0;
}
Note! In the above code we are using another character pointer t to print the characters of the
string as because we don't want to lose the starting address of the string "Hello" which is saved in
pointer variable strPtr.
Structs and Pointers
The structure pointer points to the address of a memory block where the Structure is being stored.
Like a pointer that tells the address of another variable of any data type (int, char, float) in memory.
And here, we use a structure pointer which tells the address of a structure in memory by pointing
pointer variable ptr to the structure variable.
Declare a Structure Pointer
The declaration of a structure pointer is similar to the declaration of the structure variable. So, we
can declare the structure pointer and variable inside and outside of the main() function. To declare
a pointer variable in C, we use the asterisk (*) symbol before the variable's name.
Syntax
struct structure_name *ptr;
Initialization of the Structure Pointer
ptr = &structure_variable;
We can also initialize a Structure Pointer directly during the declaration of a pointer.
struct structure_name *ptr = &structure_variable;
Access Structure member using pointer:
There are two ways to access the member of the structure using Structure pointer:
1. Using ( * ) asterisk or indirection operator and dot ( . ) operator.
2. Using arrow ( -> ) operator or membership operator.
Program to access the structure member using structure pointer and the dot operator
Let's consider an example to create a Subject structure and access its members using a structure
pointer that points to the address of the Subject variable in C.

#include <stdio.h>
// create a structure Subject using the struct keyword
struct Subject
{
// declare the member of the Course structure
char sub_name[30];
int sub_id;
char sub_duration[50];
char sub_type[50];
};

int main()
{
struct Subject sub; // declare the Subject variable
struct Subject *ptr; // create a pointer variable (*ptr)
ptr = ⊂ /* ptr variable pointing to the address of the structure variable sub */

strcpy (sub.sub_name, " Computer Science");


sub.sub_id = 1201;
strcpy (sub.sub_duration, "6 Months");
strcpy (sub.sub_type, " Multiple Choice Question");

// print the details of the Subject;


printf (" Subject Name: %s\t ", (*ptr).sub_name);
printf (" \n Subject Id: %d\t ", (*ptr).sub_id);
printf (" \n Duration of the Subject: %s\t ", (*ptr).sub_duration);
printf (" \n Type of the Subject: %s\t ", (*ptr).sub_type);

return 0;

}
Output:

Subject Name: Computer Science


Subject Id: 1201
Duration of the Subject: 6 Months
Type of the Subject: Multiple Choice Question
Program to access the structure member using structure pointer and arrow (->) operator
Let's consider a program to access the structure members using the pointer and arrow (->) operator
in C.
#include <stdio.h>

// create Employee structure


struct Employee
{
// define the member of the structure
char name[30];
int id;
int age;
char gender[30];
char city[40];
};

// define the variables of the Structure with pointers


struct Employee emp1, emp2, *ptr1, *ptr2;
int main()
{
// store the address of the emp1 and emp2 structure variable
ptr1 = &emp1;
ptr2 = &emp2;

printf (" Enter the name of the Employee (emp1): ");


scanf (" %s", &ptr1->name);

printf (" Enter the id of the Employee (emp1): ");


scanf (" %d", &ptr1->id);
printf (" Enter the age of the Employee (emp1): ");
scanf (" %d", &ptr1->age);
printf (" Enter the gender of the Employee (emp1): ");
scanf (" %s", &ptr1->gender);
printf (" Enter the city of the Employee (emp1): ");
scanf (" %s", &ptr1->city);

printf (" \n Second Employee: \n");


printf (" Enter the name of the Employee (emp2): ");
scanf (" %s", &ptr2->name);

printf (" Enter the id of the Employee (emp2): ");


scanf (" %d", &ptr2->id);
printf (" Enter the age of the Employee (emp2): ");
scanf (" %d", &ptr2->age);
printf (" Enter the gender of the Employee (emp2): ");
scanf (" %s", &ptr2->gender);
printf (" Enter the city of the Employee (emp2): ");
scanf (" %s", &ptr2->city);
printf ("\n Display the Details of the Employee using Structure Pointer");
printf ("\n Details of the Employee (emp1) \n");
printf(" Name: %s\n", ptr1->name);
printf(" Id: %d\n", ptr1->id);
printf(" Age: %d\n", ptr1->age);
printf(" Gender: %s\n", ptr1->gender);
printf(" City: %s\n", ptr1->city);

printf ("\n Details of the Employee (emp2) \n");


printf(" Name: %s\n", ptr2->name);
printf(" Id: %d\n", ptr2->id);
printf(" Age: %d\n", ptr2->age);
printf(" Gender: %s\n", ptr2->gender);
printf(" City: %s\n", ptr2->city);
return 0;
}

Output:

Enter the name of the Employee (emp1): John


Enter the id of the Employee (emp1): 1099
Enter the age of the Employee (emp1): 28
Enter the gender of the Employee (emp1): Male
Enter the city of the Employee (emp1): California

Second Employee:
Enter the name of the Employee (emp2): Maria
Enter the id of the Employee (emp2): 1109
Enter the age of the Employee (emp2): 23
Enter the gender of the Employee (emp2): Female
Enter the city of the Employee (emp2): Los Angeles

Display the Details of the Employee using Structure Pointer


Details of the Employee (emp1)
Name: John
Id: 1099
Age: 28
Gender: Male
City: California

Details of the Employee (emp2) Name: Maria


Id: 1109
Age: 23
Gender: Female
City: Los Angeles

Dynamic memory allocation in C


The concept of dynamic memory allocation in c language enables the C programmer to allocate
memory at runtime. Dynamic memory allocation in c language is possible by 4 functions of stdlib.h
header file.

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 memory can be increased while


executing program. 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>
int main(){
int n,i,*ptr,sum=0;
printf("Enter number of elements: ");
scanf("%d",&n);
ptr=(int*)malloc(n*sizeof(int)); //memory allocated using malloc
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);
free(ptr);
return 0;
}
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.

Syntax of calloc()
ptr = (castType*)calloc(n, size);
Example:
ptr = (float*) calloc(25, sizeof(float));
Example program
#include<stdio.h>
#include<stdlib.h>
int 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);
free(ptr);
return 0;
}
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)
Example program
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr, i , n1, n2;
printf("Enter size: ");
scanf("%d", &n1);
ptr = (int*) malloc(n1 * sizeof(int));
printf("Addresses of previously allocated memory:\n");
for(i = 0; i < n1; ++i)
printf("%pc\n",ptr + i);

printf("\nEnter the new size: ");


scanf("%d", &n2);
// rellocating the memory
ptr = realloc(ptr, n2 * sizeof(int));
printf("Addresses of newly allocated memory:\n");
for(i = 0; i < n2; ++i)
printf("%pc\n", ptr + i);
free(ptr);
return 0;
}
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)
Example
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main () {
char *str;
/* Initial memory allocation */
str = (char *) malloc(15);
strcpy(str, "tutorialspoint");
printf("String = %s, Address = %u\n", str, str);

/* Reallocating memory */
str = (char *) realloc(str, 25);
strcat(str, ".com");
printf("String = %s, Address = %u\n", str, str);
/* Deallocate allocated memory */
free(str);
return(0);
}

You might also like