Unit 2 - 3
Unit 2 - 3
Definition
A pointer is a variable whose value is the address
of another variable, i.e., direct address of the
memory location. This is done by using unary
operator * that returns the value of the variable
located at the address specified by its operand.
POINTERS
Syntax
Datatype *pointervariable;
Syntax Example
datatype *pointer_variable=0;
datatype *pointer_variable=NULL;
Example
Pointer Arithmetic
C allows you to perform some arithmetic operations on
pointers.
Incrementing a pointer
Incrementing a pointer is one which increases the number of
bytes of its data type.
int *ptr;
int a[]={1,2,3};
ptr=&a;
ptr++;
ptr=&a;
ptr=ptr+1;
Pointer Arithmetic
Decrementing a Pointer
Only integers can be added to pointer. It is not valid to add a float or double value
to a pointer.
A pointer variable cannot be assigned a non address value except zero.
OUTPUT
3. A void pointer cannot be dereferenced
Relational operations
A pointer can be compared with a pointer of same type or
zero.
fptr1=&a;fptr2=&b;
int result;
result=fptr1!=fptr2;
Example
Pointers and Arrays
Pointers and arrays are closely related , An array variable is
actually just a pointer to the first element in the array.
Accessing array elements using pointers is efficient way than
using array notation.
When an array is declared, compiler allocates sufficient
amount of memory to contain all the elements of the array.
Base address i.e address of the first element of the array is
also allocated by the compiler.
Pointers and Arrays Cont…
Suppose we declare an array arr,
int arr[5]={ 1, 2, 3, 4, 5 };Assuming that the base address of
arr is 1000 and each integer requires two bytes, the five
elements will be stored as follows
Pointers and Arrays Cont…
Here variable arr will give the base address, which is a
a[i][j], a will give the base address of this array, even a+0+0 will
also give the base address, that is the address of a[0][0] element.
multidimensional arrays.
4 5 6
7 8 9
10 11 12
matrix[0][0] = *(*(matrix))
matrix[i][j] = *((*(matrix)) + (i * COLS + j))
matrix[i][j] = *(*(matrix + i) + j)
matrix[i][j] = *(matrix[i] + j)
matrix[i][j] = (*(matrix + i))[j]
&matrix[i][j] = ((*(matrix)) + (i * COLS + j))
Example 3
void array_of_arrays_ver(int arr[][COLS])
{
int i, j;
for (i = 0; i < ROWS; i++)
{
for (j = 0; j < COLS; j++)
{
printf("%d\t", arr[i][j]);
}
printf("\n");
}
}
void ptr_to_array_ver(int (*arr)[COLS])
{
int i, j;
for (i = 0; i < ROWS; i++)
{
for (j = 0; j < COLS; j++)
{
printf("%d\t", (*arr)[j]);
}
arr++;
printf("\n");
}
}
Output
Double Pointer
#include <stdio.h>
#define ROWS 4
#define COLS 3
int main ()
{
// matrix of 4 rows and 3 columns
int matrix[ROWS][COLS] = {{1, 2, 3},
{4, 5, 6},
{7, 8, 9},
{10, 11, 12}};
int** pmat = (int **)matrix;
printf("&matrix[0][0] = %u\n", &matrix[0][0]);
printf("&pmat[0][0] = %u\n", &pmat[0][0]);
return 0;
}
Output
&matrix[0][0] = 2675498000
&pmat[0][0] = 1