You are on page 1of 25

Topic…………

Pointer

19-Dec-17 ME 172 : C Programming Sessional 1


POINTERS
• A pointer is a programming language object, whose value refers to (or "points to")
another value stored elsewhere in the computer memory using its address. A
pointer references a location in memory, and obtaining the value stored at that
location is known as dereferencing the pointer.
• A pointer is a variable which contains the address of another variable.

Organization of Memory

1 2 3 4
address i: INTEGR TYPE DATA

0x2143

p =&i INTEGR TYPE POINTER

19-Dec-17 ME 172 : C Programming Sessional 2


POINTERS
Declaration Dereferencing variable
Syntax:
variable type *variable_name;
For what type of The target variable
data will the
pointer be used? This syntax actually mimics the way how an ordinary variable is declared.

USE:
variable_name = &some_variable;

* and & are inverses and cancel each other out. That means *&y is equivalent to y.

19-Dec-17 ME 172 : C Programming Sessional 3


POINTERS
Declaration
Implementation example:

int x =1, y =2, z[10]; //two integers and one array declaration

int *ip; // ip is an integer type pointer Similarly one can declare:

ip = &x; //ip points to the memory of x


char *x;
double *y;
y =*ip; // y is now 1 atof(char *); etc….

*ip = 0; //x is now 0

ip = &z[0]; // ip now points to z[0]

19-Dec-17 ME 172 : C Programming Sessional 4


POINTERS
Simple examples
int x,*y;
x=1; Format specifier
y=&x; for printing
Hexadecimal
printf("x = %d\n",x); values
printf("&x = %x\n",&x);
printf("y = %x\n",y);
printf("*y = %d\n",*y);

Output
19-Dec-17 ME 172 : C Programming Sessional 5
POINTERS
Simple examples
int x,*y;
x=1;
y=&x;
printf("x = %d\n",x);
printf("&x = %x\n",&x); Output
printf("y = %x\n",y);
printf("*y = %d\n",*y);
*y = 9;
printf("after *y = 9 operation x = %d\n",x);
19-Dec-17 ME 172 : C Programming Sessional 6
POINTERS
Pointers and Function Arguments
Ordinarily in C programming language arguments are passed to function by value. So,
there is no direct way to alter the actual variable with the help of a function. A function
merely can alter the copies of actual variables of the caller function.

However, by passing pointers to the variables of interest one can easily modify the actual
variables through function.

Return type function_name(pointer type *a);


Calling method

19-Dec-17 ME 172 : C Programming Sessional 7


POINTERS
Pointers and Function Arguments
#include <stdio.h>
Method of
void sample(int *b);
declaration
void main()
{int x,*a;
x = 5;
a =&x;
printf("Before calling function x = %d\n",x);
sample(a);
printf("\nAfter calling function x = %d",x);
}
void sample(int *b)
{
*b = 6;
}

19-Dec-17 ME 172 : C Programming Sessional 8


POINTERS and ARRAYS
• In C, there is a strong relationship between pointers and arrays.
• Any operation that can be done by array subscripting can also be done by using
pointer and using pointers actually lessens the runtime.

Before going into the discussion, lets recall what we learned about arrays.

1 2 3 4

arr[0] arr[1] arr[2] arr[3]

ARRAY (say, int arr[4])


This array is stored in memory
with reference to its name. The
name points to the first element.

19-Dec-17 ME 172 : C Programming Sessional 9


POINTERS and ARRAYS
The declaration Now assume we declare an array int A[10].
int A[10]; *pa *(pa+1) *(pa+9)
defines an array A of size A: A[0] A[1] A[9]
10, that is, a block of 10
consecutive objects named pa &A[0] &A[1] pa+ 1 &A[9] pa+ 9
A[0],…,A[9] in memory.
Now the assignment x = *pa, will actually copy the element
Say, pa is an integer type pointer. of A[0] to the variable x. if pa is incremented as *(pa+1) it
int *pa; will point to the element inside A[1]. In similar manner,
Now if we declare, *(pa+i) points to the i-th element in an array.
pa = &A[0];
Remember that pa + 1 points to the next object, not the next
pa would actually point to the first
element in the array. byte.

19-Dec-17 ME 172 : C Programming Sessional 10


POINTERS and ARRAYS
 We know that the name of an array is a synonym for the location of the initial element. Therefore,
the assignment pa = &A[0] and pa = A are identical. After this declaration if you increment the
pointer as before the result will be similar.

If you are clever enough you have already guessed A[i] and *(A+i) point to the same element.
Similarly pa[i] is identical to [pa +i].

BUT there is a difference between a pointer and an array. The pointer is


actually a variable. Hence, the commands pa = a or pa++ are valid
commands. However, A++ is not a valid command!

19-Dec-17 ME 172 : C Programming Sessional 11


POINTERS and ARRAYS
Example
#include <stdio.h>
void main()
{int i,y[3],*p,*q;
for(i=0;i<3;i++) scanf("%d",&y[i]);
for(i=0;i<3;i++) printf("%d\n",y[i]);
p = &y[0];
printf("***************\n");
for(i=0;i<3;i++) {printf("%d\n",*(p+i));}
q = y;
printf("***************\n");
for(i=0;i<3;i++) {printf("%d\n",*(q+i));}
}

19-Dec-17 ME 172 : C Programming Sessional 12


POINTERS: Dynamic Memory Allocation
 From the discussion of array and pointer it is quite clear that an array can be defined as a
pointer. We have used it in case of string input in previous lecture without going into
details.
 So it means we can use int *x instead of int x[10];
 In case of arrays, if we declared an array with specified size, the compiler would allocate a
fixed memory for the array (we have seen it). But for pointer variables representing
arrays, the compiler doesn’t allocate a memory straightaway since there is no mention of
size. Hence, we need to manually allocate some contiguous memory locations.

There are quite a few functions that we can use for this purpose, alloc(), calloc(),
realloc() and malloc() are examples. To empty the memory location we use afree()
and free(). Only malloc() is discussed here.

19-Dec-17 ME 172 : C Programming Sessional 13


POINTERS: Dynamic Memory Allocation
variable name = (type *) malloc(number of blocks*sizeof(int));

If type is integer and number of blocks = 2 then,

4 bytes

1 byte

Same would happen for any other type of


variables. Target and pointer must have same type.
19-Dec-17 ME 172 : C Programming Sessional 14
POINTERS: Dynamic Memory Allocation

#include <stdio.h>
void main()
{int i,n,*p;
n = 5;
p =(int*) malloc(n*sizeof(int));
for(i=0;i<n;i++) scanf("%d",p+i);
for(i=0;i<n;i++)
printf("\n%d",*(p+i));
}

19-Dec-17 ME 172 : C Programming Sessional 15


POINTERS
There is a significant difference in strings (a type of array) and pointers. You see, a string is a
character type array and the compiler reserves certain memory blocks for those. However, if a
string is represented as a pointer, this doesn’t mean that these are fixed to some particular
memory location. Like other variables the same pointer can point to some other memory
location of choice.

Consider the example of: char amessage[]= “Mechanical”


and char *pmessage = “Mechanical”;
amessage is fixed to a memory location. But pemssage is not.
For the same reason, we had to use strcpy() function instead
of just writing string1 = string2.

19-Dec-17 ME 172 : C Programming Sessional 16


POINTERS: Arrays of Pointer.

Enough about Arrays AND


Pointers!

Lets talk about arrays who are pointers  

19-Dec-17 ME 172 : C Programming Sessional 17


POINTERS: Arrays of Pointer.
Since pointers are variables themselves, these can be stored in arrays just as other variables.
At first let us understand the declaration method and how to access to a particular element
in a one-dimension array of pointer.
For simplicity we restrict to one-dimensional arrays only.

data type *array[expression]

Name of the array

int*number[4]

LET’S SEE HOW IT WORKS!

19-Dec-17 ME 172 : C Programming Sessional 18


POINTERS: Arrays of Pointer.
int*number[4]

number[0]

number[1]

number[2]

number[3]
0 1 2

If we want to access third element of the fourth array we write the expression as
*(number[3]+2)

19-Dec-17 ME 172 : C Programming Sessional 19


POINTERS: Arrays of Pointer.
Sorting list of strings

In order to sort strings we can use character type arrays of pointers effectively. In such
cases, the pointer point to the first character of each string. Hence, we can compare
strings comfortably.
We can use strcmp() function for our aid. If strcmp(string1, string2) gives:
I. Negative value, first string precedes the second.
II. Zero, both strings are same.
III.Positive value, second string precedes the first.

19-Dec-17 ME 172 : C Programming Sessional 20


POINTERS: Arrays of Pointer.
Illustrative Example: Sort names of three clubs United, Barca, and Real in alphabetical order.

#include <stdio.h>
#include <stdlib.h>
#include<string.h>
void main()
{ int i;
char *temp,*nam[3] = {“United", “Barca", “Real"};
for(i=0;i<3;i++){if(strcmp(nam[i],nam[i+1])>0) {
temp = nam[i];
nam[i] = nam[i+1];
nam[i+1]= temp;}
}
printf("\n\n\n********\n\n");
for(i=0;i<3;i++) puts(nam[i]);
}
19-Dec-17 ME 172 : C Programming Sessional 21
POINTERS: To Functions….
A very useful feature of pointer is, through it, you can pass one function as argument
of another function, or use the function as a variable!!!!!

Let us call the argument function as guest and caller function as host.

For the guest function method of declaration is usual: data type func_name(arg1,arg2);

For the host function method of declaration is usual:

data type host_func_name(data_type (*func_name)(arg1,arg2));

19-Dec-17 ME 172 : C Programming Sessional 22


POINTERS: To Functions….Swapping
void swaph(void (*pf)(int x, int y), int p, int q);
void swapg(int a, int b);
void main()
{ int p,q;
printf("Enter x = ");
scanf("%d",&p);
printf("Enter y = ");
scanf("%d",&q);
swaph(swapg, p, q);
}
void swaph(void(*pf)(int x, int y), int p, int q)
{ (*pf)(p,q);
}
void swapg(int a, int b){
int temp;
temp = a;
a = b;
b = temp;
printf("\nAfter swapping x = %d and y = %d\n",a,b);
}
19-Dec-17 ME 172 : C Programming Sessional 23
POINTERS
ASSIGNMENTS!

1) Write a simple C program using pointer that splits a string. Suppose, you
input a string “Mustafizur/Rahman”. The program must find the slash and
output as: “First = Mustafizur; Last = Rahman”.
2) Write your own version of strcmp() library function using pointers. That
means, the function will compare two strings and find out if these are similar
or not. For a change, your function should return character instead of integer.
If two strings match, the function should return ‘y’ otherwise ‘n’.

19-Dec-17 ME 172 : C Programming Sessional 24


Thank you
The only true wisdom is in knowing; you know nothing.

Socrates

19-Dec-17 ME 172 : C Programming Sessional 25

You might also like