0% found this document useful (0 votes)
29 views

FYBCA Sem 2 C Lang Unit 2 - Pointer

1. Pointers in C store the address of other variables, functions, or pointers. They allow access to low-level memory and dynamic memory allocation. 2. Pointers are declared with a variable type followed by an asterisk, such as int* ptr. They can store addresses of variables, arrays, functions, or other pointers. 3. Pointers are useful for passing large objects to functions without copying, traversing arrays quickly, and observing changes made to shared data. Dynamic memory allocation also relies on pointers.
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)
29 views

FYBCA Sem 2 C Lang Unit 2 - Pointer

1. Pointers in C store the address of other variables, functions, or pointers. They allow access to low-level memory and dynamic memory allocation. 2. Pointers are declared with a variable type followed by an asterisk, such as int* ptr. They can store addresses of variables, arrays, functions, or other pointers. 3. Pointers are useful for passing large objects to functions without copying, traversing arrays quickly, and observing changes made to shared data. Dynamic memory allocation also relies on pointers.
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/ 14

Unit 2 –Pointers

Introduction: Defination and uses


The pointer in C language is a variable which stores the address of another variable.
This variable can be of type int, char, array, function, or any other pointer
A pointer can be used to store the memory address of other variables, functions, or
even other pointers. The use of pointers allows low-level memory access, dynamic
memory allocation, and many other functionality in C.
Syntax of C Pointers
The syntax of pointers is similar to the variable declaration in C, but we use the ( *
) dereferencing operator in the pointer declaration.
datatype * ptr;
where
• ptr is the name of the pointer.
• datatype is the type of data it is pointing to.
Operator Meaning
* Serves 2 purpose
1. Declaration of a pointer
2. Returns the value of the referenced variable
& Serves only 1 purpose
• Returns the address of a variable
Consider the following example to define a pointer which stores the address of an
integer.
int n = 10;
int* p = &n; // Variable p of type pointer is pointing to the address of the varia
ble n of type integer
Let pointer “ptr” holds the address of an integer variable or holds the address of
memory whose value(s) can be accessed as integer values through “ptr”. So to
define “ptr” we can do it in four ways, which are as following:
int *ptr;
int* ptr;
int * ptr;
int*ptr;

Prashant M. Savdekar Page 1


When Pointers are used:
Pointers are used to store and manage the addresses of dynamically allocated blocks
of memory. Such blocks are used to store data objects or arrays of objects. Most
structured and object-oriented languages provide an area of memory, called
the heap or free store, from which objects are dynamically allocated.

Pointers store addresses of the memory locations, this what everyone knows, let me
explain why sometimes it's better to use pointers instead of original variables:
• They save space: space is very precious & saving space leads to gaining
time thus better performance. Suppose you're working with very large data
types or you have yourself have created a very large object. Now if you want
to pass this object to a function, then the compiler will create a copy of this
object in the memory, then this copy will be passed to the function & then
the processing on the value will begin. In this way you're not using the
memory efficiently cos you have to create a copy of such a large object
without any good reasons. But if you pass the address of this variable to the
target function then the processing will be done directly on the original
object & hence no time or memory will be wasted on the duplication of the
original object. Thus speed & space efficiency is gained.
• They can increase speed during iterative traversal: for example if you
wish to traverse the array then you'll just write a for loop to iterate the index
value, but in actual you are incrementing the memory address. So if you're
doing performance conscious back-end coding then instead of first
incrementing the index & then updating the memory address you can
directly access the next memory location & hence performance improvement.
• Changes made are observed everywhere: suppose you have a program
with independent threads. Now instead of creating copy of the same data for
each one of them, you provide them with the address of the original value &
thus if any change is made to the value then every thread will get the latest
updates.
• Reading variables not in the same scope: I just read on Yahoo_answers
that using pointers you can access variables which were not declared in the
same scope.
& Ofcourse all time favourite Dynamic Memory Allocation is possible due to
pointers.

Example:
// C program to illustrate Pointers
#include <stdio.h>
void Pointer1()
{

Prashant M. Savdekar Page 2


int var = 20; // declare pointer variable
int* ptr; // note that data type of ptr and var must be same
ptr = &var; // assign the address of a variable to a pointer
printf("Value at ptr = %p \n", ptr);
printf("Value at var = %d \n", var);
printf("Value at *ptr = %d \n", *ptr);
}
void main()
{
Pointer1();
getch();
}
Output
Value at ptr = 0x7ffd15b5deec
Value at var = 20
Value at *ptr = 20
Pointer to array
The following is the syntax of array pointers.
datatype *variable_name[size];
Here,
datatype − The datatype of variable like int, char, float etc.
variable_name − This is the name of variable given by user.
size − The size of array variable.
int arr[10];
int *p[10]=&arr; // Variable p of type pointer is pointing to the address of an integer
array arr.

#include<stdio.h>

int main()
{
int arr[5] = { 1, 2, 3, 4, 5 };
int *ptr = arr;

printf("%p\n", ptr);
return 0;
}
Program2
int myNumbers[4] = {25, 50, 75, 100};
int *ptr = myNumbers;
int i;

Prashant M. Savdekar Page 3


for (i = 0; i < 4; i++) {
printf("%d\n", *(ptr + i));
}

Result:
25
50
75
100

/ C program to demonstrate the use of array of pointers


#include <stdio.h>

int main()
{
// declaring some temp variables
int var1 = 10;
int var2 = 20;
int var3 = 30;
// array of pointers to integers
int* ptr_arr[3] = { &var1, &var2, &var3 };
// traversing using loop
for (int i = 0; i < 3; i++) {
printf("Value of var%d: %d\tAddress: %p\n", i + 1, *ptr_arr[i], ptr_arr[i]);
}
return 0;
}
Output
Value of var1: 10 Address: 0x7fff1ac82484
Value of var2: 20 Address: 0x7fff1ac82488
Value of var3: 30 Address: 0x7fff1ac8248c
Explanation:

Prashant M. Savdekar Page 4


Pointer to a function
Pointer as a function parameter is used to hold addresses of arguments 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 affect the original
variable.
Declaration of a function pointer
Till now, we have seen that the functions have addresses, so we can create pointers
that can contain these addresses, and hence can point them.
Syntax of function pointer
return type (*ptr_name)(type1, type2…);
For example:
int (*ip) (int);
void show (int);
void(*p)(int) = &display; // Pointer p is pointing to the address of a function

Program
#include <stdio.h>
void swap(int *n1, int *n2);
void main()
{
int num1 = 5, num2 = 10;
// address of num1 and num2 is passed
swap( &num1, &num2);
printf("num1 = %d\n", num1);
printf("num2 = %d", num2);
getch();
}
void swap(int* n1, int* n2)
{
int temp;
temp = *n1;
*n1 = *n2;
*n2 = temp;
}
Output :
num1 = 10
num2 = 5

Prashant M. Savdekar Page 5


Pointer to structure
1. struct st {
2. int i;
3. float f;
4. }ref;
5. struct st *p = &ref;
Example: Access members using Pointer
To access members of a structure using pointers, we use the -> operator.

#include <stdio.h>
struct person
{
int age;
float weight;
};
int main()
{
struct person *personPtr, person1;
personPtr = &person1;

printf("Enter age: ");


scanf("%d", &personPtr->age);

printf("Enter weight: ");


scanf("%f", &personPtr->weight);

printf("Displaying:\n");
printf("Age: %d\n", personPtr->age);
printf("weight: %f", personPtr->weight);

return 0;
}
Run Code
In this example, the address of person1 is stored in the personPtr pointer using
personPtr = &person1;.

Now, you can access the members of person1 using the personPtr pointer.

By the way,

Prashant M. Savdekar Page 6


personPtr->age is equivalent to (*personPtr).age
personPtr->weight is equivalent to (*personPtr).weight

Pointers to Pointer:
As we know that, a pointer is used to store the address of a variable in C.
Pointer reduces the access time of a variable. However, In C, we can also define a
pointer to store the address of another pointer. Such pointer is known as a double
pointer (pointer to pointer). The first pointer is used to store the address of a variable
whereas the second pointer is used to store the address of the first pointer. Let's
understand it by the diagram given below.

The syntax of declaring a double pointer is given below.


int **p; // pointer to a pointer which is pointing to an integer.

Write a program to pointers to pointer.


#include<stdio.h>
#include<conio.h>
void main ()
{
int a = 10;
int *p;
int **pp;
p = &a; // pointer p is pointing to the address of a
pp = &p; // pointer pp is a double pointer pointing to the address of pointer p
printf("address of a: %x\n",p); // Address of a will be printed
printf("address of p: %x\n",pp); // Address of p will be printed

Prashant M. Savdekar Page 7


printf("value stored at p: %d\n",*p); // value stoted at the address contained by p
i.e. 10 will be printed
printf("value stored at pp: %d\n",**pp); // value stored at the address contained b
y the pointer stoyred at pp
getch();
}
Output
address of a: d26a8734
address of p: d26a8738
value stored at p: 10
value stored at pp: 10

Dynamic memory allocation

Since C is a structured language, it has some fixed rules for programming. One of
them includes changing the size of an array. An array is a collection of items stored
at contiguous memory locations.

As can be seen, the length (size) of the array above is 9. But what if there is a
requirement to change this length (size)? For example,
• If there is a situation where only 5 elements are needed to be entered in this
array. In this case, the remaining 4 indices are just wasting memory in this
array. So there is a requirement to lessen the length (size) of the array from 9 to
5.
• Take another situation. In this, there is an array of 9 elements with all 9 indices
filled. But there is a need to enter 3 more elements in this array. In this case, 3
indices more are required. So the length (size) of the array needs to be changed
from 9 to 12.
This procedure is referred to as Dynamic Memory Allocation in C.
Therefore, C Dynamic Memory Allocation can be defined as a procedure in which
the size of a data structure (like Array) is changed during the runtime.
C provides some functions to achieve these tasks. There are 4 library functions
provided by C defined under <stdlib.h> header file to facilitate dynamic memory
allocation in C programming. They are:
1. malloc()
2. calloc()

Prashant M. Savdekar Page 8


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.
C malloc() method
The “malloc” or “memory allocation” method in C is used to dynamically allocate
a single large block of memory with the specified size. It returns a pointer of type
void which can be cast into a pointer of any form. It doesn’t Initialize memory at
execution time so that it has initialized each block with the default garbage value
initially.
Syntax of malloc() in C
ptr = (cast-type*) malloc(byte-size)
For Example:

ptr = (int*) malloc(100 * sizeof(int));


Since the size of int is 4 bytes, this statement will allocate 400 bytes of memory. And,
the pointer ptr holds the address of the first byte in the allocated memory.

If space is insufficient, allocation fails and returns a NULL pointer.


Let's see the example of malloc() function.

#include<stdio.h>
#include<stdlib.h>
int main(){
intn,i,*ptr,sum=0;

Prashant M. Savdekar Page 9


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

C calloc() method:
“calloc” or “contiguous allocation” method in C is used to dynamically allocate
the specified number of blocks of memory of the specified type. it is very much
similar to malloc() but has two different points and these are:
It initializes each block with a default value ‘0’.
It has two parameters or arguments as compare to malloc().
Syntax of calloc() in C
ptr = (cast-type*)calloc(n, element-size);
here, n is the no. of elements and element-size is the size of each element.

For Example:
ptr = (float*) calloc(25, sizeof(float));
This statement allocates contiguous space in memory for 25 elements each with the
size of the float.

Prashant M. Savdekar Page 10


If space is insufficient, allocation fails and returns a NULL pointer.

Let's see the example of calloc() function.

#include<stdio.h>
#include<stdlib.h>
int main(){
intn,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.

Prashant M. Savdekar Page 11


Let's see the syntax of realloc() function.

ptr=realloc(ptr, new-size)
C free() method
“free” method in C is used to dynamically de-allocate the memory. The memory
allocated using functions malloc() and calloc() is not de-allocated on their own.
Hence the free() method is used, whenever the dynamic memory allocation takes
place. It helps to reduce wastage of memory by freeing it.
Syntax of free() in C
free(ptr);

Example 1: malloc() and free()


// Program to calculate the sum of n numbers entered by the user

#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));

if(ptr == NULL) { // if memory cannot be allocated


printf("Error! memory not allocated.");
exit(0);
}
printf("Enter elements: ");
for(i = 0; i < n; ++i) {
scanf("%d", ptr + i);
sum += *(ptr + i);
}
printf("Sum = %d", sum);

free(ptr); // deallocating the memory

getch();

Prashant M. Savdekar Page 12


}

Output
Enter number of elements: 3
Enter elements: 100
20
36
Sum = 156
Here, we have dynamically allocated the memory for n number of int.

Example 2: calloc() and free()


// Program to calculate the sum of n numbers entered by the user

#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));


if(ptr == NULL) {
printf("Error! memory not allocated.");
exit(0);
}

printf("Enter elements: ");


for(i = 0; i < n; ++i) {
scanf("%d", ptr + i);
sum += *(ptr + i);
}

printf("Sum = %d", sum);


free(ptr);
return 0;
}
Run Code
Output

Enter number of elements: 3


Enter elements: 100
20
36
Sum = 156

Prashant M. Savdekar Page 13


Example 3: realloc()
#include <stdio.h>
#include <stdlib.h>

void 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);
getch();
}
Run Code
Output

Enter size: 2
Addresses of previously allocated memory:
26855472
26855476

Enter the new size: 4


Addresses of newly allocated memory:
26855472
26855476
26855480
26855484

Prashant M. Savdekar Page 14

You might also like