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

C PRGM Unit9

Uploaded by

nabinrajak84
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)
22 views

C PRGM Unit9

Uploaded by

nabinrajak84
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/ 16

BE SEM - I

C- Programming
Unit 9: Pointers

Syllabus Unit: - 9

Fundamentals

As you know, variable is a data name that may be used to store a data value. A variable
refers to a memory location that can store only one value at a time but can very throughout the
program.

Example: -

Int num=10;

So, every variable is a memory location and every memory location have its address defined
which can be accessed using ampersand (&) operator, which denotes an address in memory.
Consider the following example,

#include <stdio.h>

int main () {

int var1;
char var2[10];

printf("Address of var1 variable: %x\n", &var1 );


printf("Address of var2 variable: %x\n", &var2 );

return 0;
}

Teksan Gharti
BE SEM - I
C- Programming
Output

Address of var1 variable: bff5a400


Address of var2 variable: bff5a3f6

Pointer: -
A pointer is a special variable that stores the address of another variable., i.e., address of the
memory location. Unlike other variables that hold values of a certain type, pointer holds the
address of a variable. For example, an integer variable holds an integer value, however an
integer pointer holds the address of an integer variable. Example….

Here, the pointer p stores the address of variable having name var.

Features of pointer.

• 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 bytes (for 16-bit compiler).

Pointer Declaration: -

Like any variable or constant, you must declare a pointer before using it to store any variable
address. The general form of a pointer variable declaration is –

type *var-name;

Here, type is the pointer's base type; it must be a valid C data type and var-name is the name
of the pointer variable. The asterisk * used to declare a pointer.

Example: - int *A;

Teksan Gharti
BE SEM - I
C- Programming
Here, “int” is the data type and “A” is the name of pointer and * is used to denote that “A”
is pointer variable and not a normal variable.

Initialize a pointer

After declaring a pointer, we initialize it like standard variables with a variable address. To get
the address of a variable, we use the ampersand (&) operator, placed before the name of a
variable whose address we need.

Pointer initialization is done with the following syntax.

pointer = &variable;

Program:-

#include <stdio.h>
int main()
{
int a=10; //variable declaration
int *p; //pointer variable declaration
p=&a; //store address of variable a in pointer p
printf("Address stored in a variable p is:%x\n",p); //accessing the address
printf("Value stored in a variable p is:%d\n",*p); //accessing the value
return 0;
}

Output:

Address stored in a variable p is:60ff08


Value stored in a variable p is:10

Teksan Gharti
BE SEM - I
C- Programming
Passing pointer to function: -

Just like any other argument, pointers can also be passed to a function as an
argument. When we pass a pointer as an argument instead of a variable then the address of the
variable is passed instead of the value. So any change made by the function using the pointer
is permanently made at the address of passed variable. This technique is known as call by
reference in C.
Syntax:-

void fname(int *var1)


{
// Code
}

//Main Code- Pass By Reference


fname(&orginal_var1);

Here, &orginal_var1 is passed as argument during calling the function fname , which is address
of orginal_var1 and * var is passed as argument in function fname function.

Simple program: -

#include <stdio.h>

void addOne(int* ptr)


{
(*ptr)++;
}

int main()
{
int* p, i = 10;
p = &i;
addOne(p);

printf("%d", *p); // 11
return 0;
}

Output: -

Teksan Gharti
BE SEM - I
C- Programming
Program to swap two number using concept “passing pointer as argument in function”.

#include <stdio.h>
void swapnum(int *num1, int *num2)
{
int tempnum;

tempnum = *num1;
*num1 = *num2;
*num2 = tempnum;
}
int main( )

{
int v1 = 11, v2 = 77 ;
printf("Before swapping:");
printf("\nValue of v1 is: %d", v1);
printf("\nValue of v2 is: %d", v2);

/*calling swap function*/


swapnum( &v1, &v2 );

printf("\nAfter swapping:");
printf("\nValue of v1 is: %d", v1);
printf("\nValue of v2 is: %d", v2);
}

Output: -

Teksan Gharti
BE SEM - I
C- Programming
Program to add the all values in the array using concept “passing pointer as argument
in function”.

#include<stdio.h>

int SumofArrNumbers(int *arr, int Size)


{
int sum = 0;
for(int i = 0; i < Size; i++)
{
sum = sum + arr[i];
}
return sum;
}
int main()
{
int i, Add, Size, a[10];
printf("Please Enter the Size of an Array : ");
scanf("%d", &Size);

printf("\nPlease Enter Array Elements : \n");


for(i = 0; i < Size; i++)
{
scanf("%d", &a[i]);
}

Add = SumofArrNumbers(a, Size);


printf("Sum of Elements in this Array = %d \n", Add);
return 0;
}

Output: -

Teksan Gharti
BE SEM - I
C- Programming
Relationship between Arrays and pointer

As we know that array is a collection of items of similar data types. And the items in an array
are stored in contagious memory locations in computers memory heap. Now consider the array
is declared as follows……

int a[5];

Now in above declaration of the array, if the first element of array a[0] is stored at memory
location 0x16 (say) then the second element a[1] of array will be stored at the memory location
adjacent to it which is 0x16 as integer occupies 4 bytes of memory.

In computers memory, it would look like

In C programming, the name of an array always points to the base address i.e.
above “a” will refer to the address 0x12. So &a[0] and ‘a’ are equal. That is why arrays and
pointers are analogous in many ways.

Consider following declaration

int *p;
int a[5];
p = a;

Now in above declaration &a[0] is equivalent to pointer variable p and a[0] is equivalent to *p
&a[1] is equivalent to p+1 and a[1] is equivalent to *p+1……

Now analyse the following operations:

p == &a[ 0 ]; //name of the array is the address of the first element


p + 2 == &a[ 2 ]; //same address

*p == a[ 0 ]; //same value
*(p + 2) == a[ 2 ]; //same value

*p + 3 //3 is added to the value of first element


*(p + 3) //points to the third element

Teksan Gharti
BE SEM - I
C- Programming

So, in general,
1) Arrays and pointers are intimately related in C and often may be used interchangeably.
2) An array name can be thought of as a constant pointer.
3) Pointers can be used to do any operation involving array subscripting.

Example: C program to print sum of 2 numbers using pointer to an array

#include <stdio.h>
int main()
{
int i, x[2], sum = 0;
int *p;
p = x; //assign the base address

printf("Enter the number:");

for( i = 0; i < 2; i++ )


{
scanf("%d",( p + i ));
sum += *(p+i); // *(p+i) equals x[i]
}
printf("Sum = %d", sum);
return 0;
}

Output:-

Enter the numbers: 1


2
sum = 3

Teksan Gharti
BE SEM - I
C- Programming
Dynamic memory allocation

As you know, an array is a collection of a fixed number of values. Once the size of an array is
declared, you cannot change it.
Consider the following example….

Array length=5
First index=0
Last index=4

As it can be seen that the length (size) of the array above made is 5. But what if there is a
requirement to change this length (size). For Example,
If there is a situation where only 3 elements are needed to be entered in this array. In this case,
the remaining 2 indices are just wasting memory in this array. So there is a requirement to
lessen the length (size) of the array from 5 to 3.

Take another situation. In this, there is an array of 5 elements with all 5 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 5 to 8.

So to solve this issue, you can allocate memory manually during run-time. This is known as
dynamic memory allocation in C programming.

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 or it is an aspect of allocating and
freeing memory according to your needs.

Dynamic memory is managed and served with pointers that point to the newly allocated space
of memory in an area which we call the heap. Now you can create and destroy an array of
elements at runtime without any problems.

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()
3) free()
4) realloc()

Teksan Gharti
BE SEM - I
C- Programming
1) malloc()
“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.

malloc tries to allocate a given number of bytes and returns a pointer to the first address
of the allocated region. If malloc fails then a NULL pointer is returned. malloc doesn't
initialize the allocated memory and reading them without initialization invokes undefined
behaviour.

Syntax:
ptr = (cast-type*) malloc(byte-size)

For Example:
ptr = (int*) malloc(5 * sizeof(int));

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

Program:- Dynamically allocate the memory using malloc()

#include <stdio.h>
#include <stdlib.h>

int main()
{
int* ptr;
int n, i;
printf("Please Enter the Size of pointer that you want to allocate : ");
scanf("%d", &n);

printf("Enter number of elements: %d\n", n);

// Dynamically allocate memory using malloc()


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

Teksan Gharti
BE SEM - I
C- Programming
// Check if the memory has been successfully
// allocated by malloc or not
if (ptr == NULL) {
printf("Memory not allocated.\n");
exit(0);
}
else
{

// Memory has been successfully allocated


printf("Memory successfully allocated using malloc.\n");

// Get the elements of the array


for (i = 0; i < n; ++i)
{
ptr[i] = i + 1;
}

// Print the elements of the array


printf("The elements of the array are: ");
for (i = 0; i < n; ++i)
{
printf("%d, ", ptr[i]);
}
printf("\n\n");
}

return 0;
}

Output: -

Teksan Gharti
BE SEM - I
C- Programming
2) calloc()
The calloc function stands for contiguous allocation. This function is used to allocate
multiple blocks of memory. It is a dynamic memory allocation function which is used to
allocate the memory to complex data structures such as arrays and structures.

Malloc function is used to allocate a single block of memory space while the calloc function is
used to allocate multiple blocks of memory space. Each block allocated by the calloc function
is of the same size.

Syntax:

ptr = (cast-type*)calloc(n, element-size);

For Example:

ptr = (int*) calloc(5, sizeof(int));

This statement allocates contiguous space in memory for 20 elements each with the size of the
int i.e 4..

Program:- Dynamically allocate the contiguous memory using calloc()

#include <stdio.h>
int main()
{
int i, * ptr, sum = 0;
int n;
printf("Please Enter the Size of pointer that you want to allocate : ");
scanf("%d", &n);

printf("Enter number of elements: %d\n", n);


ptr = calloc(n, sizeof(int));

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

Teksan Gharti
BE SEM - I
C- Programming
printf("Calculating the sequence sum of the first n terms \ n ");
for (i = 0; i < 10; ++i)
{
*(ptr + i) = i;
sum += *(ptr + i);
}

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


free(ptr);
printf("\n\n");
return 0;
}

Output: -

Difference between malloc() and calloc()

The calloc function is generally more suitable and efficient than that of the malloc function.
While both the functions are used to allocate memory space, calloc can allocate multiple blocks
at a single time. You don't have to request for a memory block every time. The calloc function
is used in complex data structures which require larger memory space.

The memory block allocated by a calloc function is always initialized to zero while in malloc
it always contains a garbage value.

3) realloc()
“realloc” or “re-allocation” method in C is used to dynamically change the memory
allocation of a previously allocated memory. In other words, if the memory previously
allocated with the help of malloc or calloc is insufficient, realloc can be used to dynamically
re-allocate memory.

Syntax:-

ptr = realloc(ptr, newSize);

where ptr is reallocated with new size 'newSize'.

Teksan Gharti
BE SEM - I
C- Programming
Program:- Dynamically reallocate the memory which is already allocated by using calloc.

#include <stdio.h>
#include <stdlib.h>

int main()
{

int* ptr;
int n, i;

n = 5;
printf("Enter number of elements: %d\n", n);

// Dynamically allocate memory using calloc()


ptr = (int*)calloc(n, sizeof(int));

// Check if the memory has been successfully


if (ptr == NULL)
{
printf("Memory not allocated.\n");
exit(0);
}
else
{
printf("Memory successfully allocated using calloc.\n");
for (i = 0; i < n; ++i)
{
ptr[i] = i + 1;
}

// Print the elements of the array


printf("The elements of the array are: ");
for (i = 0; i < n; ++i)
{
printf("%d, ", ptr[i]);
}

// Get the new size for the array


n = 10;
printf("\n\nEnter the new size of the array: %d\n", n);

// Dynamically re-allocate memory using realloc()


ptr = realloc(ptr, n * sizeof(int));

printf("Memory successfully re-allocated using realloc.\n");

// Get the new elements of the array


for (i = 5; i < n; ++i)
{

Teksan Gharti
BE SEM - I
C- Programming
ptr[i] = i + 1;
}

printf("The elements of the array are: ");


for (i = 0; i < n; ++i)
{
printf("%d, ", ptr[i]);
}

free(ptr);
}

return 0;
}

Output: -

The free Function

The memory for variables is automatically deallocated at compile time. In dynamic


memory allocation, you have to deallocate memory explicitly. If not done, you may encounter
out of memory error.

The free() function is called to release/deallocate memory. By freeing memory in your


program, you make more available for use later.

For example:

#include <stdio.h>
int main()
{
int* ptr = malloc(10 * sizeof(*ptr));
if (ptr != NULL)
{
*(ptr + 2) = 50;
printf("Value of the 2nd integer is %d",*(ptr + 2));
}
free(ptr);
}

Teksan Gharti
BE SEM - I
C- Programming
Output

=================== End Unit 9 ==========================

Teksan Gharti

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy