0% found this document useful (0 votes)
21 views51 pages

CH6 Pointers

Chapter 6 of the document focuses on pointers in C programming, detailing their declaration, initialization, and operations, as well as concepts like dynamic memory allocation. It explains how pointers provide indirect access to variables via memory addresses and discusses various types of pointers, including void and null pointers. Additionally, the chapter covers pointer arithmetic, assignment, and the importance of data types for pointers in memory management.

Uploaded by

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

CH6 Pointers

Chapter 6 of the document focuses on pointers in C programming, detailing their declaration, initialization, and operations, as well as concepts like dynamic memory allocation. It explains how pointers provide indirect access to variables via memory addresses and discusses various types of pointers, including void and null pointers. Additionally, the chapter covers pointer arithmetic, assignment, and the importance of data types for pointers in memory management.

Uploaded by

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

Chapter 6

Pointers
FE – C Programming

Prof. Namrata Jiten Patel


Assistant Professor
Dept. of Computer Engineering,
SIES Graduate School of Technology
Objectives :To provide exposure to problem-solving by developing an
algorithm, flowchart and implement the logic using C programming
language

Outcomes: Learner will be able to…


1. Understand the concept of pointers

Namrata Jiten Patel 2


Namrata Jiten Patel 3
Learning Outcomes

Fundamentals of
Declaration, initialization Operations on Pointers Concept of dynamic
pointers
and dereferencing of memory allocation.
pointers

Namrata Jiten Patel 4


Understanding memory allocation

• All computers have primary memory, also known as RAM or random-


access memory.
• For example, a computer may have 16, 32, 64, 128, 256, or 512 MB
of RAM installed.
• RAM holds the programs that the computer is currently running
along with the data they are currently manipulating
• All the variables used in a program (and indeed, the program itself)
reside in the memory when the program is executed.
• When a program in C is written and compiled, the compiler will
allocate the memory necessary to run the program.

Namrata Jiten Patel 5


Computer memory

• Int x;
• X=1000;

Namrata Jiten Patel 6


Address of Operator(&)

• Readers might have noticed that when we call certain functions in C


the & sign is used.
• For example,
• scanf(“%d”, &n);

Takes the input from the terminal and stores it in integer format in the variable
named n.

Namrata Jiten Patel 7


Pointer

• A pointer provides a way of accessing a variable without referring to


the variable directly.
• The mechanism used for this is the address of the variable.
• A program statement can refer to a variable indirectly using the
address of the variable.
• A pointer variable is a variable that holds the memory address of
another variable.
• The pointer does not hold a value in the traditional sense; instead, it
holds the address of another variable.
• They are called pointers for the simple reason that, by storing an
address, they ‘point’ to a particular point in memory.

Namrata Jiten Patel 8


Declaring Pointer

• A pointer has to be declared;


• It will have a value, a scope, a lifetime, a name; and it will occupy a
certain number of memory locations.
• The pointer operator available in C is ‘*’, called ‘value at address’
operator.
• It returns the value stored at a particular address. The value at
address operator is also called ‘indirection’ operator.
• A pointer variable is declared by preceding its name with an asterisk.

Namrata Jiten Patel 9


• The syntax for declaring a pointer variable is
datatype * pointer_variable;

• where, datatype is the type of data that the pointer is allowed to


hold the address of (that is, the type of data that the pointer is
allowed to point to) and pointer_variable is the pointer variable
name that is used to refer to the address of a variable of type
datatype.

Namrata Jiten Patel 10


• An example of a pointer declaration would be
• char *ptr;
• The above declaration should be evaluated as: ptr is a pointer to char
type data. char is not the data type of ptr.
• ptr is an identifier of type pointer and char is a data specifier that is
used to indicate what type of data is at the memory address that ptr
is holding.
• Pointers are variables that hold memory addresses. At the memory
address, held in a pointer, is a value; this value has a data type of one
of the C data types or a user-defined data type (e.g., structure).

Namrata Jiten Patel 11


Example:

int *a;
• The above declaration indicates that a is a pointer type variable that
points to int type data.
• That is, the int indicates that the pointer variable is intended to store
the address of an integer variable. Such a pointer is said to ‘point to’
an integer.
float *t;
• The above declaration represents the fact that t is a pointer type
variable that points to float type data.

Namrata Jiten Patel 12


Meaning of some pointer type
variable declarations

Namrata Jiten Patel 13


Namrata Jiten Patel 14
Why should pointers have data-type

• Point:1
• When objects of a given data type are stored consecutively in the
memory (that is, an array), each object is placed at a certain offset
from the previous object, if any, depending on its size.

Namrata Jiten Patel 15


Why should pointers have data-type

• Point:2
• A compiler that generates a code for a pointer, which accesses these
objects using pointer arithmetic, requires information on generating
offset.

Namrata Jiten Patel 16


Why should pointers have data-type

• Point:3
Sizes of various data types are basically decided by the machine
architecture and/or the implementation.

Namrata Jiten Patel 17


Initializing Pointers

• It should be noted that, unlike a simple variable that stores a value, a


pointer must be initialized with a specified address prior to its use.

• A pointer must not be used until it is assigned a meaningful address.


• To use a pointer that has not been initialized properly will cause
unpredictable results.
Namrata Jiten Patel 18
Namrata Jiten Patel 19
Indirection Operator and
Dereferencing​
• The primary use of a pointer is to access and, if appropriate, change
the value of the variable that the pointer is pointing to. ​
• The other pointer operator available in C is ‘*’, called the ‘value
at address’ operator.​
• It returns the value stored at a particular address.​
• The value at address operator is also called indirection operator
or dereference operator.​

Namrata Jiten Patel 20


#include <stdio.h>​
int main()​
{​
int num = 5;​
int *iPtr = &num;​
printf(“\n The value of num is %d”, num);​
num = 10;​
printf(“\n The value of num after num = 10 is\​
%d”, num);​
*iPtr = 15;​
printf(“\n The value of num after *iPtr = 15 is\​
%d”, num);​
return 0;​
}​
Output:​
The value of num is 5​
The value of num after num = 10 is 10​
The value of num after *iPtr = 15 is 15​

Namrata Jiten Patel 21


• The placement of the indirection operator before a pointer is said
to dereference the pointer. ​
• The value of a dereferenced pointer is not an address, but rather the
value at that address—that is, the value of the variable that the pointer
points to.​
• For example, in the preceding program, iPtr’s value is the address of
num. However, the value of iPtr dereferenced is the value of num.
Thus, the following two statements have the same effect, both
changing the value of num.​
• num = 25;​
• *iPtr = 25;​
• Similarly, a dereferenced pointer can be used in arithmetic
expressions in the same fashion as the variable to which it points.
Thus, the following two statements have the same effect.​
• num *= 2;​
• *iPtr *= 2;​

Namrata Jiten Patel 22


VOID POINTER​

• A void pointer is a special type of pointer. It can point to any data


type.​
• Its sole limitation is that the pointed data cannot be referenced
directly (the asterisk * operator cannot be used on them) since its
length is always undetermined. ​
• Therefore, type casting or assignment must be used to turn the void
pointer to a pointer of a concrete data type to which we can refer.​

Namrata Jiten Patel 23


• #include <stdio.h>​
• int main()​
• {​
• int a=5,​
• double b=3.1415;​
• void *vp;​
• vp=&a;​
• printf(“\n a= %d”, *((int *)vp));​
• vp=&b;​
• printf(“\n a= %d”, *((double *)vp));​
• return 0;​
• }​
• Output:​
• a= 5​
• b= 3.141500​
Namrata Jiten Patel 24
NULL POINTER​

• A null pointer is a special pointer that points nowhere.​


• That is, no other valid pointer to any other variable or array cell or
anything else will ever be equal to a null pointer.​
• The most straightforward way to get a null pointer in the program is
by using the predefined constant NULL, which is defined by several
standard header files, including <stdio.h>, <stdlib.h>, and <string.h>. ​
• To initialize a pointer to a null pointer, code such as the following can
be used.​
• #include <stdio.h>​
• int *ip = NULL;​

Namrata Jiten Patel 25


• #include <stdio.h>​
• int main()​
• {​
• int *p;​
• p = NULL;​
• printf(“\n The value of p is %u”, p);​
• return 0;​
• }​
• Output:​
• The value of p is 0​

Namrata Jiten Patel 26


Points to note​

• NULL is a constant that is defined in the standard library and is the equivalent of zero for a
pointer. ​
• NULL is a value that is guaranteed not to point to any location in memory.​
• #include <stdio.h>​
• int main(void)​
• {​
• char *p=NULL;​
• printf(“%s”,p);​
• return 0;​
• }​
• The C standard lays down that the argument for a %s specifier shall be a
pointer to an array of characters.​
• Since NULL is not an array of characters,
the statement “printf(“%s”,p);” shows
an undefined behaviour resulting in unpredictable or compiler defined
output.​
• ​
Namrata Jiten Patel 27
POINTER ARITHMETIC​

• If p is declared as a pointer variable of any type and it has been initialized properly,
then, just like a simple variable, any operation can be performed with *p​
• Valid operations on pointers are as follows:​
• Assignment of pointers to the same type of pointers:​
• the assignment of pointers is done symbolically. Hence no integer constant except 0
can be assigned to a pointer.​
• Adding or subtracting a pointer and an integer.​
• Subtracting or comparing two pointers (within array limits) that point to the
elements of an array.​
• Incrementing or decrementing the pointers (within array limits) that point to the
elements of an array. When a pointer to an integer is incremented by one, the
address is incremented by two (as two bytes are used for int). Such scaling factors
necessary for the pointer arithmetic are taken care of automatically by the compiler.​
• Assigning the value 0 to the pointer variable and comparing 0 with the pointer. The
pointer with address 0 points to nowhere at all​

Namrata Jiten Patel 28


• Do not attempt the following arithmetic operations on pointers. They
will not work.​
• Addition of two pointers​
• Multiplying a pointer with a number​
• Dividing a pointer with a number​

Namrata Jiten Patel 29


Assignment​

• Pointers with the assignment operators can be used if


the following conditions are met.​
• The left-hand operand is a pointer and the right-hand operand is a
null pointer constant.​
• One operand is a pointer to an object of incompatible type and the
other is a pointer to void.​
• Both the operands are pointers to compatible types.​

Namrata Jiten Patel 30


• #include <stdio.h>​
• int main()​
• {​
• int i=5;​
• int *ip;​
• void *vp;​
• ip = &i;​
• vp = ip;​
• printf(“\n *vp= %d”,*((int *)vp));​
• ip = vp;​
• printf(“\n *ip= %d”,*ip);​
• return 0;​
• }​
• Output:​
• *vp=5​
• *ip=5​
Namrata Jiten Patel 31
Addition or Subtraction with
Integers​
• The expression (arr + 3) is equivalent to the expression (&(arr[3])).​
• arr[3] is equivalent to *(arr + 3).​
• #include <stdio.h>​
• int main(void)​
• {​
• int a[] = {10, 12, 6, 7, 2};​
• int i;​
• int sum = 0;​
• int *p;​
• p = a;​
• for(i=0; i<5; i++)​
• {​
• sum += *p;​
• p++;​
• }​
• printf(“%d\n”, sum);​
• return 0;​
• }​
Namrata Jiten Patel 32
Subtraction of Pointers​
Two pointers are subtracted, as long as they point into the same array.​
- The result is the number of elements separating them.​

• #include <stdio.h>​ •To print the number of bytes


resulting from q-p, each pointer
• int main()​ may be typecast.​
• {​ #include <stdio.h>​
int main()​
• double a[2],*p,*q;​
{​
• p=a;​ double a[2],*p,*q;​
• q=p+1;​ p=a;​
q=p+1;​
• printf(“%ld\n”,q – p);​ printf(“%d\n”,(int)q-(int)p);​
• return 0;​ return 0;​
• }​ }​
Output:​
• Output:​ 8​
• 1​

Namrata Jiten Patel 33


Comparing Pointers​

• C allows pointers to be compared with each other. ​


• If two pointers compare equal to each other, then they point to the
same thing, whether it is an object or the non-existent element of the
end of an array (see arithmetic above). ​
• If two pointers point to the same thing, then they compare equal to
each other.​
• The relational operators >, <=, and so on give the result that would
be expected if the pointers point to the same array: if one pointer
compares less than another, then it points nearer to the front of the
array​

Namrata Jiten Patel 34


• #include <stdio.h>​
• int main(void)​
• {​
• int a[] = {10, 20, 30, 40, 50};​
• int i, *p;​
• for(p=a; p<=a+4; p++)​
• printf(“%d\n”, *p);​
• return 0;​
• }​
• Output:​
• 10​
• 20​
• 30​
• 40​
• 50​
• ​
• Note: Here each time p is compared with the base
address of the array.​
Namrata Jiten Patel 35
Dynamic Memory Allocation in C

• Manual allocation and freeing of memory according to your


programming needs.
• Dynamic memory is managed and served with pointers that point
to the newly allocated memory space in an area which we call the
heap.

• To sum up, the automatic memory management uses the stack, and
the C Dynamic Memory Allocation uses the heap.

Namrata Jiten Patel 36


Library used for Dynamic Memory Allocation
<stdlib.h>

Namrata Jiten Patel 37


C malloc() Function

• The C malloc() function stands for memory allocation.


• It is a function which is used to allocate a block of memory
dynamically.
• It reserves memory space of specified size and returns the null
pointer pointing to the memory location.
• The pointer returned is usually of type void.
• It means that we can assign C malloc() function to any pointer.

Namrata Jiten Patel 38


Syntax

•ptr is a pointer of cast_type.


•The C malloc() function returns a pointer to the allocated memory of
byte_size.

Example: ptr = (int *) malloc (50)

•A memory space of 50 bytes is reserved. The address of the first byte of


reserved space is assigned to the pointer ptr of type int.

Namrata Jiten Patel 39


Example

Namrata Jiten Patel 40


Notice

1.sizeof(*ptr) was used instead of sizeof(int) in order to make the


code more robust when *ptr declaration is typecasted to a different
data type later.
2.The allocation may fail if the memory is not sufficient. In this case, it
returns a NULL pointer. So, you should include code to check for a
NULL pointer.
3.Keep in mind that the allocated memory is contiguous and it can be
treated as an array. We can use pointer arithmetic to access the
array elements rather than using brackets [ ].
4.We advise to use + to refer to array elements because using
incrementation ++ or += changes the address stored by the pointer.
5.Malloc() function can also be used with the character data type as
well as complex data types such as structures.

Namrata Jiten Patel 41


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 in C.
• By freeing memory in your program, you make more available for
use later.

Namrata Jiten Patel 42


Example

Namrata Jiten Patel 43


C calloc() Function

• The C 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() in C is used to allocate multiple blocks of memory
space.
• Each block allocated by the calloc() function is of the same size.

Namrata Jiten Patel 44


Syntax and example

 The above statement is used to allocate n memory blocks of the same size.
 After the memory space is allocated, then all the bytes are initialized to zero.
 The pointer which is currently at the first byte of the allocated memory space is
returned.
 Whenever there is an error allocating memory space such as the shortage of
memory, then a null pointer is returned.

Namrata Jiten Patel 45


Example of calloc()

Namrata Jiten Patel 46


Difference between calloc and malloc

calloc Malloc
calloc() function is generally more suitable and Malloc is less preferred than calloc
efficient than that of the malloc() function
Both allocates memory Both allocates memory

calloc() in C is used to allocate multiple blocks of Malloc() function is used to allocate a


memory space single block of memory space
Each block allocated by the calloc() function is of the
same size
The calloc() function is used in complex data structures -Malloc() function can also be used
which require larger memory space with the character data type as well as
complex data types such as structures.

The memory block allocated by a calloc() in C is always malloc() in C, it always contains a


initialized to zero garbage value

Namrata Jiten Patel 47


realloc

• Using the C realloc() function, you can add more memory size to
already allocated memory.
• It expands the current block while leaving the original content as it
is.
• realloc() in C stands for reallocation of memory.
• realloc() can also be used to reduce the size of the previously
allocated memory.

Namrata Jiten Patel 48


Syntax and example

• The above statement allocates a new memory space with a specified size in the
variable newsize.
• After executing the function, the pointer will be returned to the first byte of the
memory block.
• The new size can be larger or smaller than the previous memory.
• We cannot be sure that if the newly allocated block will point to the same location
as that of the previous memory block.
• This function will copy all the previous data in the new region.
• It makes sure that data will remain safe.

Namrata Jiten Patel 49


Example

• Whenever the realloc() in C results in an unsuccessful operation, it


returns a null pointer, and the previous data is also freed

Namrata Jiten Patel 50


Thank You!!
[email protected]

Namrata Jiten Patel 51

You might also like