KEMBAR78
Unit 7 (Pointers) | PDF | Pointer (Computer Programming) | Parameter (Computer Programming)
0% found this document useful (0 votes)
6 views15 pages

Unit 7 (Pointers)

The document provides a comprehensive overview of pointers in C, explaining their definition, types, and usage. It covers various pointer concepts including pointer to pointer, pointer and array, and function returning a pointer, along with examples to illustrate their functionality. Additionally, it discusses the advantages and drawbacks of using pointers, as well as the relationship between arrays and pointers.

Uploaded by

shashikant.patel
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)
6 views15 pages

Unit 7 (Pointers)

The document provides a comprehensive overview of pointers in C, explaining their definition, types, and usage. It covers various pointer concepts including pointer to pointer, pointer and array, and function returning a pointer, along with examples to illustrate their functionality. Additionally, it discusses the advantages and drawbacks of using pointers, as well as the relationship between arrays and pointers.

Uploaded by

shashikant.patel
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/ 15

Pointers: Basics of pointers, pointer to pointer, pointer and array, pointer to array, array of pointers, function

returning a pointer
Basics of pointers

Pointers in C are used to store the address of variables or a memory location. This variable can be of any
data type i.e, int, char, function, array, or any other pointer. The size of the pointer depends on the
architecture.

The Pointer in C, is a variable that stores address of another variable. A pointer can also be used to refer to
another pointer function. A pointer can be incremented/decremented, i.e., to point to the next/ previous
memory location. The purpose of pointer is to save memory space and achieve faster execution time

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 variable n of type integer.

.
An Introduction to Pointers
Pointer Notation
Consider the declaration,
int i = 3 ;
This declaration tells the C compiler to:
(a) Reserve space in memory to hold the integer value.
(b) Associate the name i with this memory location.
(c) Store the value 3 at this location.
We may represent i’s location in memory by the memory map shown in

We see that the computer has selected memory location 65524 as the place to store the value 3. The location
number 65524 is not a number to be relied upon, because some other time the computer may choose a
different location for storing the value 3. The important point is, i’s address in memory is a number.

We can print this address number through the following program:


# include <stdio.h>
int main( )
{
int i = 3 ;
printf ( "Address of i = %u\n", &i ) ;
printf ( "Value of i = %d\n", i ) ;
return 0 ;
}
The output of the above program would be:
Address of i = 65524
Value of i = 3
Look at the first printf( ) statement carefully. ‘&’ used in this statement is C’s ‘address of’ operator. The
expression &i returns the address of the variable i, which in this case happens to be 65524. Since 65524
represents an address, there is no question of a sign being associated with it. Hence it is printed out using %u,
which is a format specifier for printing an unsigned integer. We have been using the ‘&’ operator all
the time in the scanf( ) statement.

The other pointer operator available in C is ‘*’, called ‘value at address’ operator. It gives the value
stored at a particular address. The ‘value at address’ operator is also called ‘indirection’ operator.

Observe carefully the output of the following program:


# include <stdio.h>
int main( )
{
int i = 3 ;
printf ( "Address of i = %u\n", &i ) ;
printf ( "Value of i = %d\n", i ) ;
printf ( "Value of i = %d\n", *( &i ) ) ;
return 0 ;
}
The output of the above program would be:
Address of i = 65524
Value of i = 3
Value of i = 3
Note that printing the value of *( &i ) is same as printing the value of i.
The expression &i gives the address of the variable i. This address can be collected in a variable, by saying,
j = &i ;
But remember that j is not an ordinary variable like any other integer variable. It is a variable that contains the
address of other variable (i in this case). Since j is a variable, the compiler must provide it space in the
memory. Once again, the memory map shown in Figure 9.2 would illustrate the contents of i and j.

As you can see, i’s value is 3 and j’s value is i’s address.
But wait, we can’t use j in a program without declaring it. And since j is a variable that contains the address
of i, it is declared as,
int *j ;
This declaration tells the compiler that j will be used to store the address of an integer value. In other words, j
points to an integer. How do we justify the usage of * in the declaration,
int *j ;
Let us go by the meaning of *. It stands for ‘value at address’. Thus, int *j would mean, the value at the
address contained in j is an int.

Here is a program that demonstrates the relationships we have been discussing.


# include <stdio.h>
int main( )
{
int i = 3 ;
int *j ;
j = &i ;
printf ( "Address of i = %u\n", &i ) ;
printf ( "Address of i = %u\n", j ) ;
printf ( "Address of j = %u\n", &j ) ;
printf ( "Value of j = %u\n", j ) ;
printf ( "Value of i = %d\n", i ) ;
printf ( "Value of i = %d\n", *( &i ) ) ;
printf ( "Value of i = %d\n", *j ) ;
return 0 ;
}
The output of the above program would be:
Address of i = 65524
Address of i = 65524
Address of j = 65522
Value of j = 65524
Value of i = 3
Value of i = 3
Value of i = 3

What are Pointers?


A pointer is a variable whose value is the address of another variable, i.e., direct address of the memory location.
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 is the same asterisk used for multiplication. However, in this
statement the asterisk is being used to designate a variable as a pointer. Take a look at some of the valid pointer
declarations −
int *ip; /* pointer to an integer */
double *dp; /* pointer to a double */
float *fp; /* pointer to a float */
char *ch /* pointer to a character */

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 variable n of type integer.

Example
# include <stdio.h>
int main( )
{
int myAge = 43; // An int variable
int* ptr = &myAge; // A pointer variable, with the name ptr, that stores the address of myAge

// Output the value of myAge (43)


printf("%d\n", myAge);

// Output the memory address of myAge (0x7ffe5367e044)


printf("%p\n", &myAge);

// Output the memory address of myAge with the pointer (0x7ffe5367e044)


printf("%p\n", ptr);
return 0 ;
}

Types of Pointers
There are eight different types of pointers which are as follows −
 Null pointer
 Void pointer
 Wild pointer
 Dangling pointer
 Complex pointer
 Near pointer
 Far pointer
 Huge pointer

Null Pointer

You create a null pointer by assigning the null value at the time of pointer declaration.
This method is useful when you do not assign any address to the pointer. A null pointer always contains value
0.
Example
Following is the C program for the null pointer −

#include <stdio.h>
int main(){
int *ptr = NULL; //null pointer
printf("The value inside variable ptr is:%d",ptr);
return 0;
}
Output
When the above program is executed, it produces the following result −
The value inside variable ptr is:
0

Void Pointer

It is a pointer that has no associated data type with it. A void pointer can hold addresses of any type and can be
typecast to any type.
It is also called a generic pointer and does not have any standard data type.
It is created by using the keyword void.

Example
Following is the C program for the void pointer −
#include<stdio.h>
int main()
{
int a=2;
void *ptr;
ptr= &a;
printf("After Typecasting, a = %d", *(int *)ptr);
return 0;
}

Output
When the above program is executed, it produces the following result −
After Typecasting a=2;

Wild Pointer

Wild pointers are also called uninitialized pointers. Because they point to some arbitrary memory location and
may cause a program to crash or behave badly.
This type of C pointer is not efficient. Because they may point to some unknown memory location which may
cause problems in our program. This may lead to the crashing of the program.
It is advised to be cautious while working with wild pointers.
Example
Following is the C program for the wild pointer −

#include <stdio.h>
int main(){
int *p; //wild pointer
printf("%d",*p);
return 0;
}
Process returned -1073741819 (0xC0000005) execution time : 1.206 s
Press any key to continue
i.e. you won’t get output, some compilers show error message at output

Advantage of pointer
1) Pointer reduces the code and improves the performance, it is used to retrieving strings, trees, etc. and
used with arrays, structures, and functions.
2) We can return multiple values from a function using the pointer.
3) It makes you able to access any memory location in the computer's memory.
4) Pointers save memory space.
5) Pointers are used with data structures. They are useful for representing two-dimensional and multi-
dimensional arrays.
6) An array, of any type, can be accessed with the help of pointers, without considering its subscript range.
7) Pointers are used for file handling.
8) Pointers are used to allocate memory dynamically.

Drawbacks of Pointers:
1) If pointers are pointed to some incorrect location then it may end up reading a wrong value.
2) Erroneous input always leads to an erroneous output
3) Segmentation fault can occur due to uninitialized pointer.
4) Pointers are slower than normal variable
5) It requires one additional dereferences step
6) If we forgot to deallocate a memory then it will lead to a memory leak.

C Double Pointer (Pointer to Pointer)


A pointer to a pointer is a form of multiple indirection, or a chain of pointers. Normally, a pointer contains the
address of a variable. When we define a pointer to a pointer, the first pointer contains the address of the second
pointer, which points to the location that contains the actual value as shown below.

A variable that is a pointer to a pointer must be declared as such. This is done by placing an additional asterisk
in front of its name. For example, the following declaration declares a pointer to a pointer of type int −
int **var;

When a target value is indirectly pointed to by a pointer to a pointer, accessing that value requires that the
asterisk operator be applied twice, as is shown below in the example –
#include <stdio.h>
int main () {

int var;
int *ptr;
int **pptr;

var = 3000;

/* take the address of var */


ptr = &var;

/* take the address of ptr using address of operator & */


pptr = &ptr;

/* take the value using pptr */


printf("Value of var = %d\n", var );
printf("Value available at *ptr = %d\n", *ptr );
printf("Value available at **pptr = %d\n", **pptr);
printf("Value available at *ptr = %d\n", ptr );
printf("Value available at **pptr = %d\n", pptr);

return 0;
}
Array and Pointer

Pointer Array
A pointer is a place in memory that keeps address An array is a single, pre allocated chunk of
of another place inside contiguous elements (all of the same type), fixed in
size and location.
Allows us to indirectly access variables. In other Expression a[4] refers to the 5 th element of the
words, we can talk about its address rather than its array a.
value
Pointer can’t be initialized at definition Array can be initialized at definition. Example int
num[] = { 2, 4, 5}
Pointer is dynamic in nature. The memory They are static in nature. Once memory is allocated
allocation can be resized or freed later , it cannot be resized or freed dynamically

Pointer to array

Arrays and pointers are closely related in C. In fact an array declared as int A[10]; can be accessed using its
pointer representation. The name of the array A is a constant pointer to the first element of the array. So A can
be considered a const int*. Since A is a constant pointer, A = NULL would be an illegal statement. Arrays and
pointers are synonymous in terms of how they use to access memory. But, the important difference between
them is that, a pointer variable can take different addresses as value whereas, in case of array it is fixed.
Consider the following array:

In C , name of the array always points to the first element of an array. Here, address of first element of an
array is &age[0]. Also, age represents the address of the pointer where it is pointing. Hence, &age[0] is
equivalent to age. Note, value inside the address &age[0] and address age are equal. Value in address &age[0]
is age[0] and value in address age is *age. Hence, age[0] is equivalent to *age.
C arrays can be of any type. We define array of ints, chars, doubles etc. We can also define an array of
pointers as follows. Here is the code to define an array of n char pointers or an array of strings.
char* A[n];
we can store address of an array in a pointer and access any element stored in that array.

In a pointer to an array, we just have to store the base address of the array in the pointer variable. We know in
the arrays that the base address of an array can be represented in three forms, let us see the syntax of how we
can store the base address in a pointer variable:
*ptr = &arr;
*ptr = arr;
*ptr = &arr[0];

In all the above cases, ptr will store the base address of the array.

Let's see an example


Int k[]={1,4,12,2};
Int* ptr =&k

First element of an array can be accessed by dereferencing the pointer i.e: *ptr
As array element are located in contiguous memory location s it is possible to access every element of an
array if we know address of at least any element of the array.
//Program to find the sum of six numbers with arrays and pointers.
#include <stdio.h>
int main () {

int k[]={1,4,12,1,2};
int *ptr=&k;

printf("first Element of array = %d\n", *ptr );


printf("second Element of array = %d\n", *(ptr+1) );
printf("third Element of array = %d\n", *(ptr+2) );
printf("fourth Element of array = %d\n", *(ptr+3));
printf("fifth Element of array = %d\n", *(ptr+4) );

return 0;
}

Array of Pointer
An array of pointers can be declared just like we declare the arrays of char, float, int, etc. The syntax for
declaring an array of pointers would be:
data_type *name_of_array [array_size];
Now, let us take a look at an example for the same,
int *ary[55]
This one is an array of a total of 55 pointers. In simple words, this array is capable of holding the addresses a
total of 55 integer variables. Think of it like this- the ary[0] will hold the address of one integer variable, then
the ary[1] will hold the address of the other integer variable, and so on.
Example
Let us take a look at a program that demonstrates how one can use an array of pointers in C:
#include<stdio.h>
#define SIZE 10
int main()
{
int *arr[3];
int p = 40, q = 60, r = 90, i;
arr[0] = &p;
arr[1] = &q;
arr[2] = &r;
for(i = 0; i < 3; i++)
{
printf(“For the Address = %d\t the Value would be = %d\n”, arr[i], *arr[i]);
}
return 0;
}
The output generated out of the program mentioned above would be like this:
For the Address = 387130656 the Value would be = 40
For the Address = 387130660 the Value would be = 60
For the Address = 387130664 the Value would be = 90

How Does it Work?


Take a look at how we assigned the addresses of the pointers p, q, and r. We first assign the p variable’s
address to the 0th element present in the array. In a similar manner, the 1st and 2nd elements of the array will
be assigned with the addresses of q and r. At this very point, the array, arr would look like this:
The arr[i] provides the address of the array’s ith element. Thus, the arr[0] would return the address of the
variable p, the arr[1] would return the address of the pointer q, and so on. We use the * indirection operator to
get the value present at the address. Thus, it would be like this:
*arr[i]
Thus, *arr[0] would generate the value at the arr[0] address. In a similar manner, the *arr[1] would generate
the value at the arr[1] address, and so on.

What is a Pointer to an Array


The array pointer is an alternative name to a pointer to an array. We generally make use of this pointer for
accessing the various components of any given array. The pointer ptr basically focuses on the 0th component
of any given array. Likewise, one can easily declare a point that is capable of pointing to a whole array- rather
than only a single array component.

What is an Array of Pointers?


It refers to an array of various pointer variables, also called the pointer arrays. One can easily create separate
pointer variables pointing towards different ranges of values. And we can also create a single integer array of
pointers pointing towards all the available values.

Parameters Pointer to an Array Array of Pointers


Uses and A user creates a pointer for storing the A user creates an array of pointers that basically
Purposes address of any given array. acts as an array of multiple pointer variables.
Alternative It is alternatively known as an array These are alternatively known as pointer arrays.
Names pointer.
Allocation One can allocate these during the run One can allocate these during the compile time
time.
Initialization You cannot initialize a pointer to the You can easily initialize an array at the
at Definition definition. definition level.
Nature It is dynamic in nature. It is static in nature.
Resizing One can easily resize the allocated Once we declare the size of an array, we cannot
memory of a pointer later at any given resize it any time we want according to our
time. requirements.
Type of A typical pointer variable is capable of The size of any given array decides the total
Storage storing only a single variable within. number of variables that it can store within.

function returning a pointer


We have already seen a function can return data of types int , float, char etc. Similarly, a function can return a
pointer to data. The syntax of a function returning a pointer is as follows.
We can pass pointers to the function as well as return pointer from a function. But it is not recommended to
return the address of a local variable outside the function as it goes out of scope after function returns.

Syntax: type *function_name(type1, type2, ...);

Some examples:

int *func(int, int); // this function returns a pointer to int


double *func(int, int); // this function returns a pointer to double

#include<stdio.h>
int *return_pointer(int *, int); // this function returns a pointer of type int

int main()
{
int i, *ptr;
int arr[] = {11, 22, 33, 44, 55};
i = 4;

printf("Address of arr = %u\n", arr);

ptr = return_pointer(arr, i);

printf("\nAfter incrementing arr by 4 \n\n");

printf("Address of ptr = %u\n\n" , ptr);


printf("Value at %u is %d\n", ptr, *ptr);

// signal to operating system program ran fine


return 0;
}

int *return_pointer(int *p, int n)


{
p = p + n;
return p;
}
Expected Output:

Address of arr = 2686736

After incrementing arr by 4

Address of ptr = 2686752

Value at 2686752 is 55

Since the name of an array is a pointer to the 0th element of the array. Here we are passing two arguments to
the function return_pointer(). The arr is passed using call by reference (notice that name of the array is not
preceded by & operator because the name of the array is a constant pointer to the 0th element of the 1-D
array) and i is passed using call by value. Inside the function pointer p is incremented by n and reassigned
to p. Finally, the pointer p is returned to the main() function and reassigned to ptr.

Never return a pointer to local variable from a function.


Call by value vs. call by reference
The parameters of functions can be passed in two ways:

1. Call by value: A copy of the variable is passed to the function.


2. Call by reference: An address of the variable is passed to the function.

Call by value in C
o In call by value method, the value of the actual parameters is copied into the formal parameters.
In other words, we can say that the value of the variable is used in the function call in the call
by value method.
o In call by value method, we can not modify the value of the actual parameter by the formal
parameter.
o In call by value, different memory is allocated for actual and formal parameters since the value
of the actual parameter is copied into the formal parameter.
o The actual parameter is the argument which is used in the function call whereas formal
parameter is the argument which is used in the function definition.
#include <stdio.h>
void swap(int , int); //prototype of the function
int main()
{
int a = 10;
int b = 20;
printf("Before swapping the values in main a = %d, b = %d\n",a,b); // printing the value of a an
d b in main
swap(a,b);
printf("After swapping values in main a = %d, b = %d\n",a,b); // The value of actual
parameters do not change by changing the formal parameters in call by value, a = 10, b = 20
}
void swap (int a, int b)
{
int temp;
temp = a;
a=b;
b=temp;
printf("After swapping values in function a = %d, b = %d\n",a,b); // Formal parameters, a = 20,
b = 10
}
Output:
Before swapping the values in main a = 10, b = 20
After swapping values in function a = 20, b = 10
After swapping values in main a = 10, b = 20

Call by reference in C
o In call by reference, the address of the variable is passed into the function call as the actual
parameter.
o The value of the actual parameters can be modified by changing the formal parameters since
the address of the actual parameters is passed.
o In call by reference, the memory allocation is similar for both formal parameters and actual
parameters. All the operations in the function are performed on the value stored at the address
of the actual parameters, and the modified value gets stored at the same address.

#include <stdio.h>
void swap(int *, int *); //prototype of the function
int main()
{
int a = 10;
int b = 20;
printf("Before swapping the values in main a = %d, b = %d\n",a,b); // printing the value of a an
d b in main
swap(&a,&b);
printf("After swapping values in main a = %d, b = %d\n",a,b); // The values of actual paramete
rs do change in call by reference, a = 10, b = 20
}
void swap (int *a, int *b)
{
int temp;
temp = *a;
*a=*b;
*b=temp;
printf("After swapping values in function a = %d, b = %d\n",*a,*b); // Formal parameters, a = 2
0, b = 10
}
Output:
Before swapping the values in main a = 10, b = 20
After swapping values in function a = 20, b = 10
After swapping values in main a = 20, b = 10

You might also like