pointers
DESCRIPTION
ProgrammingTRANSCRIPT
ME 172Introduction to C Programming
Language
Cyrus Ashok Arupratan AtisLecturer, Dept. of ME, BUET
Mohd. Aminul HoqueLecturer, Dept. of ME, BUETSourav SahaLecturer, Dept. of ME, BUET
04/22/23 ME 172 : C Programming Sessional 1
2
C Programming language
ME-172
CLASS-8DATE: April 22, 2023
04/22/23 ME 172 : C Programming Sessional
Topic…………
Pointer
304/22/23 ME 172 : C Programming Sessional
• 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.
04/22/23 ME 172 : C Programming Sessional 4
POINTERS
Organization of Memory
1 2 3 4
0x2143
i:
p =&i
address INTEGR TYPE DATA
INTEGR TYPE POINTER
5
Syntax:variable type *variable_name;
This syntax actually mimics the way how an ordinary variable is declared.
Declaration
04/22/23 ME 172 : C Programming Sessional
POINTERS
For what type of data will the pointer be used?
The target variable
USE:variable_name = &some_variable;
* and & are inverses and cancel each other out. That means *&y is equivalent to y.
Dereferencing variable
6
Implementation example:Declaration
04/22/23 ME 172 : C Programming Sessional
POINTERS
int x =1, y =2, z[10]; //two integers and one array declaration
int *ip; // ip is an integer type pointer
ip = &x; //ip points to the memory of x
y =*ip; // y is now 1
*ip = 0; //x is now 0
ip = &z[0]; // ip now points to z[0]
Similarly one can declare:
char *x;double *y;atof(char *); etc….
Simple examplesint 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);
704/22/23 ME 172 : C Programming Sessional
POINTERS
Format specifier for printing Hexadecimal values
Output
Simple examples
8
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);
04/22/23 ME 172 : C Programming Sessional
POINTERS
Output
904/22/23 ME 172 : C Programming Sessional
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
1004/22/23 ME 172 : C Programming Sessional
POINTERSPointers and Function Arguments
#include <stdio.h>void sample(int *b);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;}
Method of declaration
1104/22/23 ME 172 : C Programming Sessional
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).
1204/22/23 ME 172 : C Programming Sessional
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;}
• 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.
1304/22/23 ME 172 : C Programming Sessional
POINTERS and ARRAYS
Before going into the discussion, lets recall what we learned about arrays.
1 2 3 4
ARRAY (say, int arr[4])
arr[0] arr[1] arr[2] arr[3]
This array is stored in memory with reference to its name. The name points to the first element.
14
A: A[0] A[1] A[9]
&A[0] &A[1] &A[9]
The declaration int A[10];
defines an array A of size 10, that is, a block of 10
consecutive objects namedA[0],…,A[9] in memory.
pa pa+ 1 pa+ 9
*pa *(pa+1) *(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.
04/22/23 ME 172 : C Programming Sessional
POINTERS and ARRAYS
Now assume we declare an array int A[10].
Say, pa is an integer type pointer.int *pa;
Now if we declare,pa = &A[0];
pa would actually point to the firstelement in the array.
15
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.
04/22/23 ME 172 : C Programming Sessional
POINTERS and ARRAYS
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!
1604/22/23 ME 172 : C Programming Sessional
POINTERS and ARRAYS
#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));}}
Example
04/22/23 ME 172 : C Programming Sessional 17
CLASS PERFORMANCE 2!!!
POINTERS and ARRAYS
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!!
04/22/23 ME 172 : C Programming Sessional 18
POINTERS and ARRAYS
#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;}
Solution
1904/22/23 ME 172 : C Programming Sessional
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.
2004/22/23 ME 172 : C Programming Sessional
POINTERS: Dynamic Memory Allocationvariable name = (type *) malloc(number of blocks*sizeof(int));
If type is integer and number of blocks = 2 then,
1 byte
4 bytes
Same would happen for any other type of variables. Target and pointer must have same type.
2104/22/23 ME 172 : C Programming Sessional
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));}
2204/22/23 ME 172 : C Programming Sessional
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.
2304/22/23 ME 172 : C Programming Sessional
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);}
2404/22/23 ME 172 : C Programming Sessional
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.
2504/22/23 ME 172 : C Programming Sessional
POINTERS: Arrays of Pointer.
Enough about Arrays AND Pointers!
Lets talk about arrays who are pointers
2604/22/23 ME 172 : C Programming Sessional
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!
2704/22/23 ME 172 : C Programming Sessional
POINTERS: Arrays of Pointer.
int*number[4]
number[0]
number[1]
number[2]
number[3]
If we want to access third element of the fourth array we write the expression as*(number[4]+2)
0 1 2
2804/22/23 ME 172 : C Programming Sessional
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.
2904/22/23 ME 172 : C Programming Sessional
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]);}
3004/22/23 ME 172 : C Programming Sessional
POINTERS: Arrays of Pointer.
CLASS PERFORMANCE 4: Sort names of four clubs United, Barca, Chelsea, and Real in reverse
of alphabetical order.
3104/22/23 ME 172 : C Programming Sessional
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));
3204/22/23 ME 172 : C Programming Sessional
POINTERS: To Functions….Swappingvoid 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);}
3304/22/23 ME 172 : C Programming Sessional
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’.
3404/22/23 ME 172 : C Programming Sessional
Thank youThe only true wisdom is in knowing; you know nothing.
Socrates