Pointers Part1
Pointers Part1
PART I
1. Pointer
1.1. Introduction
1.2. Pointer Concept
1.2.1. Pointer Constant
1.2.2. Pointer Value
1.2.3. Pointer Variable
1.10.Review Questions
1.1. INTRODUCTION
Pointers are one of the derived data types in C.
Some of the advantages of pointers are listed below:
A pointer enables us to access a variable that is defined outside the function.
Pointers are more efficient in handling the data tables.
Pointers reduce the length and complexity of a program.
The use of a pointer array to character strings save data storage space in memory.
The real power of C lies in the proper use of pointers.
10
65510
Variable Name
Variable value
Variable address
Memory is divided into number of storage cells called locations. Out of these the addresses, the
system assigns some addresses of the memory locations to the variables. These memory locations assigned
to the variables by the system are called pointer values. For example, the address 65510 which is assigned to
the variable i is a pointer value.
GITAM UNIVERSITY
Page 2
data type
*ptr_name;
This tells the compiler three things about the variable ptr_name.
1. The asterisk ( * ) tells that the variable ptr_name is a pointer variable.
2. ptr_name needs a memory location.
3. ptr_name points to a variable of type data type.
For example,
int *pi;
Declares the variable p as a pointer variable that points to an integer data type. Remember that the type int
refers to the data type of the variable being pointed by pi.
GITAM UNIVERSITY
Page 3
Initializing Pointers
Once a pointer variable has been declared, it can be made to point to a variable using statement such
as
ptr_name=&var;
Which cause ptr_name to point to var. Now ptr_name contains the address of var. This is known
as pointer initialization.
Before a pointer is initialized it should not be used.
*ptr_name
EXAMPLE 1: Write a C program to illustrate accessing of variable using pointer variable.
#include<stdio.h>
int main( )
{
int i=10, * ptr;
ptr = &i;
printf(\n OUTPUT : \n);
printf(\n The Address of i = %u,&i);
printf(\n The value of i = %d , i );
printf(\n The value of ptr = %u , ptr);
printf(\n The value of i = %d,*(&i));
printf(\n The value of i = %d, *ptr);
printf(\n The Address of ptr = %u,&ptr);
return 0;
}
OUTPUT:
The Address of i = 8342
The Value of i = 10
The Value of ptr = 8342
The Value of i = 10
The Value of i = 10
The Address of ptr = 8338
The above program illustrates how to access the variable using pointers. After finding the first
statement i=10, the compiler creates a variable i with a value of 10 at a memory location. Then
coming to line 2 and 3 a pointer variable pi is create and initialized with the address of the i
variable. Then the compiler automatically provides a link between these two variables as follows.
i
ptr
Variable Name
Variable Value
10
8342
8342
8338
Variable Address
NOTE: Pointer variable always points to an address of the variable .Following statements
is not valid with respect to pointers.
int i=10, k, *ptr=&i;
k=ptr; // pointer value cannot be accessed by integer
ptr=65506(constant); // we cannot directly assign a value to a pointer variable.
GITAM UNIVERSITY
Page 4
Example 2:
The following code illustrates how to declare int, char and float pointers. Here we have
declared three variables of type int, float and char ,also three pointer variables points to int, float and
char. Remember here pf points to the value of type float but its type is unsigned integer only.
Dangling Pointers
A pointer variable should contain a valid address. A pointer variable which does not contain a valid address
is called dangling pointer. For example, consider the following declaration,
int *pi;
This declaration indicates that pi is a pointer variable and the corresponding memory location should contain
address of an integer variable. But, the declaration will not initialize the memory location and memory
contains garbage value.
NOTE: We cannot use a pointer variable to the register variable. The reason is that, user does not know
the address of the register variable. So we are not able to use pointer variable on register variables.
Pointer variables may be subtracted from one another. This is helpful while finding array boundaries.
Be careful while performing subtraction of two pointers.
Pointer variables can be used in comparisons, but usually only in a comparison to NULL.
We can also use increment/decrement operators with pointers this is performed same as
adding/subtraction of integer to/from pointer.
1.4.1.
Pointer Expression
Like other variables, pointer variables can be used in expressions. For example, if p1 and p2 are two
valid pointers ,then the following statements are valid.
a = *p1 + *p2;
sum = sum + *p1;
z = 10 / *p2;
f = *p1 * i;
NOTE: be careful while writing pointer expressions .The expression *p++ will result in the
increment of the address of p by data type times and points to the new value. Whereas the
expression (*p) ++ will increments the vale at the address. If you are not properly coded you
will get some unwanted result.
GITAM UNIVERSITY
Page 7
1.4.2.
NULL Pointer
A null pointer has a value reserved for indicating that the pointer does not refer to a valid object.
Null pointers are mostly used to represent conditions such as the end of a list of unknown length or the
failure to perform some action. A pointer variable which is set to NULL, either during definition or during
execution. The following statement demonstrates how we could define a pointer with an initial value of
NULL.
int * P=NULL ; int *ptr = \0 ;
In most implementations, a null pointer contains address 0, which may be a valid or invalid address
depending on the operating system. If we dereference the pointer P when it is NULL, we will most likely get
a run-time error because NULL is not valid address. A NULL pointer is defined as a special pointer. It can
be used along with memory management functions.
This declaration tells compiler to allocate a memory for the variable ptr_ptr in which address of a pointer
variable which points to value of type data type can be stored.
Syntax for initialization
ptr_ptr=&ptr_name;
This initialization tells the compiler that now ptr_ptr points to the address of a pointer variable.
**ptr_ptr;
Accessing the element value
It is equalent to *(*(&ptr_name));
Example 5:
The above program illustrates the use of pointers to pointers. Here, using two indirection operators the
data item 16 can be accessed (i.e., *ppi refers to pi and **ppi refers to i).
1.6.1.
Casting Pointer
When assigning a memory address of a variable of one type to a pointer that points to another type it
is best to use the cast operator to indicate the cast is intentional (this will remove the warning).
Example 6:
int V = 101;
float *P = (float *) &V; /* Casts int address to float */
Removes warning, but is still a somewhat unsafe thing to do.
1.6.2.
A pointer to void is a generic type that is not associated with a reference type. It is neither the
address of a character nor an integer, nor a float nor any other type. It is compatible for assignment purposes
only with all other pointer types. A pointer of any reference type can be assigned to a pointer to void type. A
pointer to void type can be assigned to a pointer of any reference type. Certain library functions return void
pointer results. No cast is needed to assign an address to a void pointer or from a void pointer to another
pointer type. Where as a pointer to void cannot be deference unless it is cast.
Example 7:
int V = 101;
float f=98.45;
void *G = &V;
// No warning , VOID POINTER
printf (%d,*((int*)G));
// Now it will display 101
float *P = G;
// No warning, still not safe
printf (%f,*((float*)G)); // Now it will display 98.45
S[1]
H
1001
S[2]
E
1002
S[3]
L
1003
S[4]
L
1004
S[5]
O
\0
1005
String array
Address
P
1000
We cannot assign a string to another. But, we can assign a char pointer to another char pointer.
Example:
GITAM UNIVERSITY
Page 9
1.8.1.
Instead of passing the values of the variables to the called function, we pass their addresses, so that
the called function can change the values stored in the calling function. This is known as "call by
reference", since we are referencing the variables addresses. Here the addresses of actual arguments in the
calling function are copied into formal arguments of the called function. Here the formal parameters should
be declared as pointer variables to store the address. The following shows the swap function modified from a
"call by value" to a "call by reference". Note that the values are now swapped when the control is returned
to main function.
Example 8: Write a C program to swap two numbers, use variable addresses as function arguments.
Call by Reference
1.8.2.
The way function returns an int, float and char, it can return a pointer. To make a function return a
pointer it has to be explicitly mentioned in the calling function as well as in the function declaration.
Three things should be done to avail the feature of functions return pointer.
1. Declaration of function returning pointer
2. Declaring pointer and assigning function call
3. Defining function returning pointer
Syntax for declaration of function returning pointer
Example 9 :
#include<stdio.h>
int * max(int *,int *) ;
int main( )
{
int a,b, * ptr;
printf(\n Enter the value of a and b: );
scanf(%d %d,&a,&b);
ptr = max(&a ,&b);
printf(\n Max = %d,* ptr);
}
Function Declaration
int * max(int * pa, int * pb )
{
if(*pa > *pb )
return (pa);
else
return (pb);
}
OUTPUT:
Enter the value of a and b: 10 25 User input
Max = 25 Program output.
The execution of the program as follows,
Execution of the program starts at main.
Two variables and b are created and initialized at run-time.
A pointer variable is created and initialized with the return value of the function max ().
Once the control is transferred from function main () to max (), it got executed and returns the
pointer value to main().
Here we are having the address of the maximum variable address to display it just use
indirection operator (*).
NOTE: Function return pointer does not have any advantage except in the handling of strings.
GITAM UNIVERSITY
Page 11
1.8.3.
Pointers to Functions
Pointer to a function (also known as function pointer) is a very powerful feature of C. Function
pointer provides efficient and elegant programming technique. Function pointers are less error prone than
normal pointers since we will never allocate or de-allocate memory for the functions. Every variable with
the exception of register has an address. We have seen how we can refer variables of type char, int and float.
Through their addresses, by using pointers. Functions exist in memory just like variables. C will allow you
to define pointers to functions. Just like variables, a function name gives the starting address of function
stored in memory.
The below code illustrate how to get the address of a function.
Like declaring pointer variables, we can define pointers to functions variables and store the address of
a function. The below figure illustrate how function pointer can be represented.
main
// Definition of main( ) function
display
f_ptr
Functions in Memory.
The syntax for declaring pointer to function as follows,
The next after the declaration is calling the function using function pointer. before calling takes place we
must initialize the function pointer with the address of the function.
The syntax for this assignment,
f_ptr=function_name;
After this assignment we need to call the function, the syntax associated with the function call is as follows,
(*f_ptr)(arguments);
This is another way of calling the function. There are no changes in the declaration of the function body.
The below program simulates a simple calculator using function pointers.
Example 10:
Constant Pointer
A pointer is said to be constant pointer when the address its pointing to cannot be changed. Once a
pointer holds an address, it cannot change it. This means a constant pointer, if already pointing to an address,
cannot point to a new address. If we see the example above, then if ptr would have been a constant pointer,
then the third line would have not been valid.
A constant pointer is declared as :
1.9.2.
Pointer to Constant
This concept is easy to understand as the name simplifies the concept. Yes, as the name itself suggests, this
type of pointer cannot change the value at the address pointed by it. A pointer to a constant cannot change
the value at the address its pointing to.
A pointer to a constant is declared as:
const <type-of-pointer> * <name-of-pointer>;
Example 12: PointerConstant.c
#include<stdio.h>
int main(void)
{
char ch = c;
const char * ptr = &ch; // A pointer constant
*ptr = a; // WRONG!!! Cannot change the value at address pointed by ptr.
return 0;
}
OUTPUT: PointerConstant.c: In function main:
PointerConstant.c:6: error: assignment of read-only location *ptr.
So now we know the reason behind the error above ie we cannot change the value pointed to by a
constant pointer.
GITAM UNIVERSITY
Page 15
1.10.
REVIEW QUESTIONS
4. Write a function that accept 2 values and swap using call by reference.
THE - END
GITAM UNIVERSITY
Page 16