Vous êtes sur la page 1sur 34

ME 172

Introduction to C Programming
Language
Cyrus Ashok Arupratan Atis
Lecturer, Dept. of ME, BUET

Mohd. Aminul Hoque


Lecturer, Dept. of ME, BUET

Sourav Saha
Lecturer, Dept. of ME, BUET
12/21/15

ME 172 : C Programming Sessional

ME-172

C
Programming language

CLASS-8
DATE: December 21, 2015

12/21/15

ME 172 : C Programming Sessional

Topic

Pointer

12/21/15

ME 172 : C Programming Sessional

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

addres
s

i:

INTEGR TYPE
DATA

p
=&i

INTEGR TYPE
POINTER

0x2143

12/21/15

ME 172 : C Programming Sessional

POINTERS

Declaration
For what type
of data will
the pointer be
used?

Dereferencing
variable

Syntax:
variable type *variable_name;

The target
variable

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.
12/21/15

ME 172 : C Programming Sessional

POINTERS

Declaration

Implementation example:
int x =1, y =2, z[10];
declaration

//two integers and one array

int *ip; // ip is an integer type pointer


ip = &x; //ip points to the memory of x
y =*ip; // y is now 1

Similarly one can


declare:
char *x;
double *y;
atof(char *); etc.

*ip = 0; //x is now 0


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

ME 172 : C Programming Sessional

POINTERS

Simple examples
int x,*y;
x=1;
y=&x;
printf("x = %d\n",x);
printf("&x = %x\n",&x);
printf("y = %x\n",y);
printf("*y = %d\n",*y);

Format specifier
for printing
Hexadecimal
values

Output
12/21/15

ME 172 : C Programming Sessional

POINTERS

Simple examples
int x,*y;
x=1;
y=&x;
printf("x = %d\n",x);
printf("&x = %x\n",&x);
printf("y = %x\n",y);
printf("*y = %d\n",*y);
*y = 9;
printf("after *y = 9 operation x =
%d\n",x);
12/21/15

ME 172 : C Programming Sessional

Output

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

12/21/15

ME 172 : C Programming Sessional

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;
}
12/21/15

ME 172 : C Programming Sessional

10

POINTERS

Class
Performance 1!
Using pointer and a separate function write a program to swap
two variables. (e.g. if two variables are a=5 and b=10, swap their
values to a=10 and b=5).

12/21/15

ME 172 : C Programming Sessional

11

POINTERS
#include <stdio.h>
void swap(int *a, int *b);
void main()
{int x,y,*p,*q;
x = 5;
y = 10;
p = &x;
q = &y;
printf("Before swapping x = %d\ty =
%d\n",x,y);
swap(p,q);
printf("\nAfter swapping x = %d\ty =
%d\n",x,y);
}
void swap(int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
12/21/15

ME 172 : C Programming Sessional

12

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
arr[0
]
This array is stored in
memory with reference to
its name. The name points
to the first element.
12/21/15

2
arr[1
]

3
arr[2
]

4
arr[3
]

ARRAY (say, int


arr[4])
ME 172 : C Programming Sessional

13

POINTERS and ARRAYS


The declaration
int A[10];
defines an array A of size
10, that is, a block of 10
consecutive objects named
A[0],,A[9] in memory.
Say, pa is an integer type pointer.
int *pa;
Now if we declare,
pa = &A[0];
pa would actually point to the first
element in the array.

12/21/15

Now assume we declare an array int


*(pa+9)
*pa *(pa+1)
A[10].
A: A[0]

pa

A[1]

&A[0] &A[1]

A[9]

pa+ 1

&A[9]

pa+ 9

Now the assignment x = *pa, will actually copy the element


of A[0] to the variable x. if pa is incremented as *(pa+1) it
will point to the element inside A[1]. In similar manner,
*(pa+i) points to the i-th element in an array.
Remember that pa + 1 points to the next object, not the next
byte.

ME 172 : C Programming Sessional

14

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!

12/21/15

ME 172 : C Programming Sessional

15

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));}
} 12/21/15
ME 172 : C Programming Sessional

16

POINTERS and ARRAYS


CLASS PERFORMANCE 2!!!

Write a program using pointer that counts


the number of characters in a string. This can
be done using strlen() function. DO NOT
USE IT!!

12/21/15

ME 172 : C Programming Sessional

17

POINTERS and ARRAYS


Solutio
n

#include <stdio.h>
int strcnt(char *a);
void main()
{int i,*p;
char s[12];
gets(s);
p = s;
i = strcnt(p);
printf("\nNumber of characters in input string is \t=
%d",i);
}
int strcnt(char *a)
{
int count=0;
for(count=0;*a!='\0';a++)
count++;
return count;
}
12/21/15

ME 172 : C Programming Sessional

18

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 doesnt
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.
12/21/15

ME 172 : C Programming Sessional

19

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.
12/21/15

ME 172 : C Programming Sessional

20

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));
}

12/21/15

ME 172 : C Programming Sessional

21

POINTERS: Dynamic Memory Allocation

CLASS PERFORMANCE
3!!
USING DYNAMIC MEMORY ALLOCATION DECLARE
AN INTEGER ARRAY AS POINTER TO TAKE 5
INTEGERS AS INPUTS. FIND OUT THEIR AVERAGE
IN A SINGLE ELEMENT FLOAT TYPE ARRAY
DECLARED AS POINTER.

12/21/15

ME 172 : C Programming Sessional

22

POINTERS: Dynamic Memory Allocation


#include <stdio.h>
#include<math.h>
void main()
{int i,n,*p;
float sum=0.0,avg,*q;
n = 5;
p =(int*) malloc(n*sizeof(int));
for(i=0;i<n;i++) scanf("%d",p+i);
for(i=0;i<n;i++)
sum+=*(p+i);
avg = sum/n;
q = (float *) malloc(1*sizeof(float));
printf("\nAverage: \t = %f",avg);
}
12/21/15

ME 172 : C Programming Sessional

23

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 doesnt 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.

12/21/15

ME 172 : C Programming Sessional

24

POINTERS: Arrays of Pointer.

Enough about Arrays AND


Pointers!
Lets talk about arrays who are
pointers
12/21/15

ME 172 : C Programming Sessional

25

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]

LETS SEE HOW IT WORKS!

12/21/15

ME 172 : C Programming Sessional

26

POINTERS: Arrays of Pointer.


int*number[4]
number[0]
number[1]
number[2]
number[3]
0

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

12/21/15

ME 172 : C Programming Sessional

27

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.

12/21/15

ME 172 : C Programming Sessional

28

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]);
12/21/15
ME 172 : C Programming Sessional
}

29

POINTERS: Arrays of Pointer.

CLASS PERFORMANCE 4: Sort


names of four clubs United, Barca,
Chelsea, and Real in reverse of
alphabetical order.

12/21/15

ME 172 : C Programming Sessional

30

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));

12/21/15

ME 172 : C Programming Sessional

31

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);
}
12/21/15
ME 172 : C Programming Sessional

32

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.

12/21/15

ME 172 : C Programming Sessional

33

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

12/21/15

ME 172 : C Programming Sessional

34

Vous aimerez peut-être aussi