Fundamental of Programming C Lecturer Omid Jafarinezhad Lecture

  • Slides: 46
Download presentation
Fundamental of Programming (C) Lecturer: Omid Jafarinezhad Lecture 8 Pinter Department of Computer Engineering

Fundamental of Programming (C) Lecturer: Omid Jafarinezhad Lecture 8 Pinter Department of Computer Engineering 1 Sharif University of Technology

Pointer – Lecture 8 Outline • Defining and using Pointers • Operations on pointers

Pointer – Lecture 8 Outline • Defining and using Pointers • Operations on pointers – Arithmetic – Logical • Pointers and Arrays • Memory Management for Pointers Department of Computer Engineering 2 Sharif University of Technology

Pointer – Lecture 8 Pointer Fundamentals • When a variable is defined the compiler

Pointer – Lecture 8 Pointer Fundamentals • When a variable is defined the compiler (linker/loader actually) allocates a real memory address for the variable – int x; // &x = 22 f 54; – &x = 22 f 54; // Error x & * 22 F 54 0000 522 F 5 0000 22 F 56 0000 22 F 57 00000011 • When a value is assigned to a variable, the value is actually placed to the memory that was allocated – x = 3; // * (&x) = 3; – *x = 3; // Error Department of Computer Engineering 3 Sharif University of Technology

Pointer – Lecture 8 Pointer Fundamentals • When the value of a variable is

Pointer – Lecture 8 Pointer Fundamentals • When the value of a variable is used, the contents in the memory are used & * – y = x; 22 F 54 0000 x – y = *(&x); 522 F 5 0000 22 F 56 0000 22 F 57 00000011 • &x can get the address of x (referencing operator &) • The address can be passed to a function: – scanf("%d", &x); • The address can also be stored in a variable … Department of Computer Engineering 4 Sharif University of Technology

Pointer – Lecture 8 Pointers • To declare a pointer variable type * Pointer.

Pointer – Lecture 8 Pointers • To declare a pointer variable type * Pointer. Name; • For example: int x; int * p; //p is a int pointer // char *p 2; p 1 = &x; /* Initializing p 1 */ Initializing Department of Computer Engineering 5 x p & * 22 F 50 ? 22 F 51 ? 22 F 52 ? 22 F 53 ? 22 F 54 00 522 F 5 02 22 F 56 2 F 22 F 57 50 … Sharif University of Technology

Pointer – Lecture 8 Initializing Pointers • Like other variables, always initialize pointers before

Pointer – Lecture 8 Initializing Pointers • Like other variables, always initialize pointers before using them!!! Department of Computer Engineering 6 * 22 F 50 ? 22 F 51 ? 22 F 52 ? 22 F 53 Compiler p 22 F 54 ? 00 522 F 5 02 22 F 56 2 F 22 F 57 50 x … Sharif University of Technology Developer void main() { int x; int *p; Don’t scanf("%d", p); /* */ p = &x; scanf("%d", p); /* Correct */ } &

Pointer – Lecture 8 Using Pointers • You can use pointers to access the

Pointer – Lecture 8 Using Pointers • You can use pointers to access the values of other variables, i. e. the contents of the memory for other variables • To do this, use the * operator (dereferencing operator) – Depending on different context, * has different meanings • For example: int n, m = 3, *p; p = &m; // Initializing n = *p; *p printf("%dn", n); // 3 printf("%dn", *p); // 3 *p *P = 10; *P printf("%dn", n); // 3 printf("%dn", *p); // 10 *p Department of Computer Engineering & * & * n n m 3 m 3 m 10 p p 7 3 3 Sharif University of Technology

Pointer – Lecture 8 An Example int m = 3, n = 100, *p,

Pointer – Lecture 8 An Example int m = 3, n = 100, *p, *q; p = &m; printf("m is %dn", *p); // 3 m++; printf("now m is %dn", *p); // 4 p = &n; printf("n is %dn", *p); // 100 *p = 500; printf("now n is %dn", n); // 500 q = &m; *q = *p; printf("now m is %dn", m); // 500 Department of Computer Engineering 8 & * & * m 3 m 4 n 100 p p p q q q & * & m 4 m 500 n p p p q q q Sharif University of Technology * 500

Pointer – Lecture 8 Pointer Assignment & int a = 2, b = 3;

Pointer – Lecture 8 Pointer Assignment & int a = 2, b = 3; int *p 1, *p 2; p 1 = &a; p 2 = &b; printf("%p %p", p 1 , p 2); * b 3 a 2 p 1 p 2 & * *p 1 = *p 2; printf("%d %d", *p 1, *p 2); b 3 a 3 p 2 = p 1; printf("%p %p", p 1, p 2); printf("%p %p", &p 1, &p 2); p 1 Department of Computer Engineering p 2 9 Sharif University of Technology

Pointer – Lecture 8 An Example int i = 25; int *p; p =

Pointer – Lecture 8 An Example int i = 25; int *p; p = &i; & p 22 ff 40 22 ff 41 Flow of address is complier dependent 22 ff 42 22 ff 43 i 22 ff 44 printf("%x %x", &p, &i); // 22 ff 40 22 ff 44 printf("%x %p", p, p); // 22 ff 44 0022 ff 44 printf("%d %d", i, *p); // 25 25 Department of Computer Engineering 10 Sharif University of Technology *

Pointer – Lecture 8 Constant Pointers • A pointer to const data does not

Pointer – Lecture 8 Constant Pointers • A pointer to const data does not allow modification of allow the data through the pointer const int a = 10, b = 20; a = 5; // Error const int *p; int *q; p = &a; *p = 100; // Error : p is (const int *) Error p = &b; q = &a; *q = 100; // OK !!! OK Department of Computer Engineering 11 Sharif University of Technology

Pointer – Lecture 8 Constant Pointers int x; /* define x */ int y;

Pointer – Lecture 8 Constant Pointers int x; /* define x */ int y; /* define y */ /*ptr is a constant pointer to an integer that can be modified through ptr, but ptr always points to the same memory location */ int * const ptr = &x; *ptr = 7; /* allowed: *ptr is not const */ ptr = &y; /* error: cannot assign new address */ Department of Computer Engineering 12 Sharif University of Technology

Pointer – Lecture 8 Constant Pointers int x = 5; /* initialize x */

Pointer – Lecture 8 Constant Pointers int x = 5; /* initialize x */ int y; /* define y */ /*ptr is a constant pointer to a constant integer. ptr always points to the same location; the integer at that location cannot be modified */ const int * const ptr = &x; *ptr = 7; /* error: cannot assign new value */ ptr = &y; /* error: cannot assign new address */ Department of Computer Engineering 13 Sharif University of Technology

Pointer – Lecture 8 Pointer to pointer int main(void) { int s = 1;

Pointer – Lecture 8 Pointer to pointer int main(void) { int s = 1; int t = 1; int *ps = &s; int **pps = &ps; int *pt = &t; **pps = 2; pt = ps; *pt = 3; return 0; } & * & * s 1 s 2 t 1 t 1 ps ps ps pps pt pt pt Department of Computer Engineering 14 Sharif University of Technology

Pointer – Lecture 8 Multiple indirection int a = 3; int *b = &a;

Pointer – Lecture 8 Multiple indirection int a = 3; int *b = &a; int **c = &b; int ***d = &c; int ****f = &d; Department of Computer Engineering & * a 3 b c d f 15 Sharif University of Technology

Pointer – Lecture 8 NULL Pointer • Special constant pointer NULL – Points to

Pointer – Lecture 8 NULL Pointer • Special constant pointer NULL – Points to no data – Dereferencing illegal – To define, include <stdlib. h> or <stdlib. h> <stdio. h> – int *q = NULL; Department of Computer Engineering 16 Sharif University of Technology

Pointer – Lecture 8 Generic Pointers: void * • void *: a pointer to

Pointer – Lecture 8 Generic Pointers: void * • void *: a pointer to anything * type cast: tells the compiler to change an object’s type (for type checking purposes – does not modify the object in any way) void *p; int i; char c; p = &i; p = &c; putchar(*(char *)p); • Lose all information about what type of thing is pointed to – Reduces effectiveness of compiler’s type-checking – Can’t use pointer arithmetic Department of Computer Engineering 17 Sharif University of Technology

Pointer – Lecture 8 Arithmetic Operations • A pointer may be incremented or decremented

Pointer – Lecture 8 Arithmetic Operations • A pointer may be incremented or decremented – An integer may be added to or subtracted from a pointer. – Pointer variables may be subtracted from one another int a, b; int *p = &a, *q = &b; p = p + q ; // Error p = p * q; // Error p = p / q; // Error p = p - q; // OK p = p + 3; p += 1. 6; // Error p %= q; // Error Department of Computer Engineering 18 Sharif University of Technology

Pointer – Lecture 8 Arithmetic Operations • When an integer is added to or

Pointer – Lecture 8 Arithmetic Operations • When an integer is added to or subtracted from a pointer, the new pointer value is changed by the integer times the number of bytes in the data variable the pointer is pointing to – For example, if the pointer p contains the address of a double precision variable and that address is 234567870, then the statement: p = p + 2; // 234567870 + 2 * sizeof(double) would change p to 234567886 Department of Computer Engineering 19 Sharif University of Technology

Pointer – Lecture 8 Arithmetic Operations pointer + number pointer – number & char

Pointer – Lecture 8 Arithmetic Operations pointer + number pointer – number & char *p; char a; char b; p = &a; p -= 1; int *p; int a; int b; In each, p now points to b !!! (complier dependent) subtracts 1*sizeof(char) to the memory address p = &a; p -= 1; b a p subtracts 1*sizeof(int) to the memory address Pointer arithmetic should be used cautiously Department of Computer Engineering 20 Sharif University of Technology *

Pointer – Lecture 8 Logical Operations & • Pointers can be used in comparisons

Pointer – Lecture 8 Logical Operations & • Pointers can be used in comparisons int a[10], *p, *q , i; p = &a[2]; q = &a[5]; i = q - p; /* i is 3*/ i = p - q; /* i is -3 */ a[2] = a[5] = 0; i = *p - *q; // i = a[2] – a[5] if (p < q). . . ; /* true */ q if (p == q). . . ; /* false */ q if (p != q). . . ; /* true */ q Department of Computer Engineering 21 * p q [0] ? [1] ? [2] ? [3] ? [4] ? [5] ? [6] ? [7] ? [8] ? [9] ? Sharif University of Technology

Pointer – Lecture 8 Pointers and Arrays • the value of an array name

Pointer – Lecture 8 Pointers and Arrays • the value of an array name is also an address • In fact, pointers and array names can be used interchangeably in many (but not all) cases • The major differences are: – Array names come with valid spaces where they "point" to. And you cannot "point" the names to other places – Pointers do not point to valid space when they are created. You have to point them to some valid space (initialization) Department of Computer Engineering 22 Sharif University of Technology

Pointer – Lecture 8 Pointers and Arrays Array pointer to the initial (0 th)

Pointer – Lecture 8 Pointers and Arrays Array pointer to the initial (0 th) array element a &a[0] a[i] *(a+i) &a[i] a + i Example: int a, *p; p=&a; *p = 1; p[0] = 1; a [0] p [1] int a[ 10 ], *p; p = &a[2]; p[0] = 10; p[1] = 10; printf("%d", p[3]); int a[ 10 ], *p; a[2] = 10; a[3] = 10; printf("%d", a[5]); p[0] p[1] p[2] p[3] p[4] p[5] p[6] p[7] [2] [3] [4] [5] [6] [7] [8] [9] Department of Computer Engineering 23 Sharif University of Technology

Pointer – Lecture 8 Pointers and Arrays Array pointer to the initial (0 th)

Pointer – Lecture 8 Pointers and Arrays Array pointer to the initial (0 th) array element a &a[0] a[i] *(a+i) &a[i] a + i int i; array[10]; for (i = 0; i < 10; i++) { array[i] = …; } 0 a 1 2 3 a + 1 a + 2 a + 3 int *p; int array[10]; for (p = array; p < &array[10]; p++) { *p = …; } These two blocks of code are functionally equivalent Department of Computer Engineering 24 Sharif University of Technology

Pointer – Lecture 8 An Array Name is Like a Constant Pointer • Array

Pointer – Lecture 8 An Array Name is Like a Constant Pointer • Array name is like a constant pointer which points to the first element of the array int * const a int a[10], *p, *q; p = a; /* p = &a[0] */ q = a + 3; /* q = &a[0] + 3 */ a ++; /* Error !!! */ Department of Computer Engineering 25 Sharif University of Technology

Pointer – Lecture 8 Example int a[10], i; int *p = a; // int

Pointer – Lecture 8 Example int a[10], i; int *p = a; // int *p = &a[0]; for (i = 0; i < 10; i++) scanf("%d", a + i); // scanf("%d", &a[i]); for (i = 9; i >= 0; --i) printf("%d", *(p + i)); // printf("%d", a[i]); //printf("%d", p[i]); for (p = a; p < &a[10]; p++) printf("%d", *p); Department of Computer Engineering 26 Sharif University of Technology

Pointer – Lecture 8 An example p & * p q int a[10], *p,

Pointer – Lecture 8 An example p & * p q int a[10], *p, *q; q [0] ? p = &a[2]; [1] ? q = p + 3; [2] ? [3] ? p = q – 1; [4] ? [4] 123 p++; [5] ? [5] 123 q--; [6] ? *p = 123; [7] ? [8] ? *q = *p; [9] ? q = p; printf("%d", *q); /* printf("%d", a[5]) */ Department of Computer Engineering 27 Sharif University of Technology

Pointer – Lecture 8 An Example int a[10], *p; a++; //Error a--; // Error

Pointer – Lecture 8 An Example int a[10], *p; a++; //Error a--; // Error a += 3; //Error p = a; // p = &a[0]; p ++; //OK p--; // Ok P +=3; // Ok Department of Computer Engineering 28 Sharif University of Technology

Pointer – Lecture 8 Strings • In C, strings are just an array of

Pointer – Lecture 8 Strings • In C, strings are just an array of characters – Terminated with ‘’ character – Arrays for bounded-length strings – Pointer for constant strings (or unknown length) unknown length char H e l l str 1[15] = "Hello, world!“; o , char str 1[] char *str 2 H e l l o , Department of Computer Engineering w o r l d ! = "Hello, world!"; w 29 o r l d Sharif University of Technology

Pointer – Lecture 8 An Example char *str, s[] = "ALIREZA"; printf("%s", s); //

Pointer – Lecture 8 An Example char *str, s[] = "ALIREZA"; printf("%s", s); // ALIREZA printf(s) printf("%s", s + 3); // REZA scanf("%s", s); scanf("%s", &s[0]); str = s; while(* str) putchar(*str++); // *s++ : Error Department of Computer Engineering 30 Sharif University of Technology

Pointer – Lecture 8 An Example void copy 1( char * const char *

Pointer – Lecture 8 An Example void copy 1( char * const char * void char const s 1, const char const s 2) { int i; /* counter */ /* loop through strings */ for ( i = 0; ( s 1[ i ] = s 2[ i ] ) != ''; i++ ); /* do nothing in body */ } void copy 2(char *s 1, const char *s 2) char { /* loop through strings */ for ( ; ( *s 1 = *s 2 ) != ''; s 1++, s 2++ ); /* do nothing in body */ } Department of Computer Engineering 31 Sharif University of Technology

Pointer – Lecture 8 Multi-Dimensional Arrays int a[row][col]; a[row][col] *(*(a + row) + col)

Pointer – Lecture 8 Multi-Dimensional Arrays int a[row][col]; a[row][col] *(*(a + row) + col) a[row][col] *(a[row] + col) &a[row][col] a[row] + col a a[0][0] a[0] + 2 scanf(" %d ", &a[0][0]) scanf(" %d ", a[0]) printf (" %d ", a[0][0]) printf(" %d ", *a[0]) scanf(" %d ", &a[2][2]) scanf(" %d ", a[2]+ 2) printf (" %d ", a[2][2]) printf(" %d ", *(a[2] + 2)) a[0] � [0][0] [0][1] [0][2] [0][3] [0][4] [0][5] [0][6] [0][7] [0][8] [0][9] a[1] � [1][0] [1][1] [1][2] [1][3] [1][4] [1][5] [1][6] [1][7] [1][8] [1][9] a[2] � [2][0] [2][1] [2][2] [2][3] [2][4] [2][5] [2][6] [2][7] [2][8] [2][9] a[3] � [3][0] [3][1] [3][2] [3][3] [3][4] [3][5] [3][6] [3][7] [3][8] [3][9] a[4] � [4][0] [4][1] [4][2] [4][3] [4][4] [4][5] [4][6] [4][7] [4][8] [4][9] Department of Computer Engineering 32 Sharif University of Technology

Pointer – Lecture 8 Array of Pointers char *suit[ 4 ] = { "Hearts",

Pointer – Lecture 8 Array of Pointers char *suit[ 4 ] = { "Hearts", "Diamonds", "Clubs", "Spades" }; suit[0] � H e a r t s suit[1] � D i a m o n d suit[2] � C l u b s suit[3] � S p a d e s Department of Computer Engineering 33 s Sharif University of Technology

Pointer – Lecture 8 Array of Pointers int a=1, b=2, c=3, d=4; int *k[4]

Pointer – Lecture 8 Array of Pointers int a=1, b=2, c=3, d=4; int *k[4] = {&a, &b, &c, &d}; k[0] � a 1 k[1] � b k[2] � k[3] � & * k[0] k[1] k[2] k[3] a 1 2 b 2 c 3 d 4 printf("%d %d", *k[0], *k[1], *k[2], *k[3]); Department of Computer Engineering 34 Sharif University of Technology

Pointer – Lecture 8 Pointer to Function #include <stdio. h> void f 1(float a){

Pointer – Lecture 8 Pointer to Function #include <stdio. h> void f 1(float a){ printf("F 1 %g", a); } void f 2(float a){ printf("F 2 %g", a); } A function pointer is defined in the same way as a function prototype, but the function name is replaced by the pointer name prefixed with an asterisk and encapsulated with parenthesis Example: int (*fptr)(int, char) fptr = some_function; int main(){ void (*ptr. F)(float a); ptr. F = f 1; ptr. F(12. 5); ptr. F = f 2; ptr. F(12. 5); getch(); return 0; } Department of Computer Engineering (*ftpr)(3, 'A'); some_function(3, 'A'); 35 Sharif University of Technology

Pointer – Lecture 8 Array of Functions #include<stdio. h> void func 1() { printf("Function

Pointer – Lecture 8 Array of Functions #include<stdio. h> void func 1() { printf("Function 1 Calledn"); } void func 2() { printf("Function 2 Calledn"); } void func 3() { printf("Function 3 Calledn"); } int main(int argc, char *argv[]) { void (*ptr[3]) () = {func 1, func 2, func 3}; int k = 0; for(k = 0; k < 3; k++) ptr[k](); getch(); return 0; } Department of Computer Engineering 36 Sharif University of Technology

Pointer – Lecture 8 Passing Arrays to Functions #include <stdio. h> void display(int a)

Pointer – Lecture 8 Passing Arrays to Functions #include <stdio. h> void display(int a) { printf("%d", a); } int main() { int c[] = {2, 3, 4}; display(c[2]); //Passing array element c[2] only return 0; } Department of Computer Engineering 37 Sharif University of Technology

Pointer – Lecture 8 Passing Arrays to Functions #include <stdio. h> float average(float a[]);

Pointer – Lecture 8 Passing Arrays to Functions #include <stdio. h> float average(float a[]); // float average(float *a) int main(){ float avg, c[]={23. 4, 55, 22. 6, 3, 40. 5, 18}; avg=average(c); /* Only name of array is passed as argument */ printf("Average age=%. 2 f", avg); return 0; } float average(float a[]){ // float average(float int I; float avg, sum=0. 0; for(I = 0; I < 6; ++i) sum += a[i]; avg = (sum / 6); return avg; *a) void func (int* x); /* this is a pointer */ void func (int x[]); /* this is a pointer */ void func (int x[10]); /* this is a pointer */ } Department of Computer Engineering 38 Sharif University of Technology

Pointer – Lecture 8 Passing Arrays to Functions #include <stdio. h> float average(float a[],

Pointer – Lecture 8 Passing Arrays to Functions #include <stdio. h> float average(float a[], int count); // float average(float *a, int count) int main(){ float avg, c[]={23. 4, 55, 22. 6, 3, 40. 5, 18}; avg=average(c, 6); /* Only name of array is passed as argument */ printf("Average age=%. 2 f", avg); return 0; } float average(float a[], int count){ // float average(float int I; float avg, sum = 0. 0; for(I = 0; I < count; count ++i) sum += a[i]; avg = (sum / 6); return avg; *a) void func (int* x); /* this is a pointer */ void func (int x[]); /* this is a pointer */ void func (int x[10]); /* this is a pointer */ } Department of Computer Engineering 39 Sharif University of Technology

Pointer – Lecture 8 Passing Arrays to Functions #include <stdio. h> void f 1(float

Pointer – Lecture 8 Passing Arrays to Functions #include <stdio. h> void f 1(float *a) { a[1] = 100; } void f 2(float a[]){ a[2] = 200; } void print. Arrat(float a[]) { int i = 0; for(; i < 6; i++) printf("%g ", a[i]); } int main(){ float c[]={23. 4, 55, 22. 6, 3, 40. 5, 18}; f 1(c); print. Arrat(c); puts(""); f 2(c); print. Arrat(c); getch(); return 0; } Department of Computer Engineering Passing Array By Reference 23. 4 55 22. 6 3 40. 5 18 23. 4 100 22. 6 3 40. 5 18 23. 4 55 200 3 40. 5 18 40 Sharif University of Technology

Pointer – Lecture 8 Passing 2 D, 3 D, … Array to Functions •

Pointer – Lecture 8 Passing 2 D, 3 D, … Array to Functions • Only the first dimension may be omitted – int m[5][7]; – func(m); – void func(int a[5][7]) {. . . } – void func(int a[][7]) {. . . } Department of Computer Engineering 41 Sharif University of Technology

Pointer – Lecture 8 Allocating Memory for a Pointer // The following program is

Pointer – Lecture 8 Allocating Memory for a Pointer // The following program is wrong! // This one is correct: #include <stdio. h> int main() { int *p; { Don’t int *p; scanf("%d", p); int a; return 0; p = &a; } scanf("%d", p); return 0; } Department of Computer Engineering 42 Sharif University of Technology

Pointer – Lecture 8 malloc #include <stdlib. h> • Prototype: void *malloc(size_t size); –

Pointer – Lecture 8 malloc #include <stdlib. h> • Prototype: void *malloc(size_t size); – function returns the address of the first byte – programmers responsibility to not lose the pointer • Example: Key int *ptr; ptr = (int *)malloc(sizeof(int)); // new allocation 10 ptr Memory 0 previously allocated 1 2 3 4 5 6 Department of Computer Engineering 7 8 43 9 10 11 12 13 14 15 16 Sharif University of Technology

Pointer – Lecture 8 free • Prototype: void free(void *ptr) #include <stdlib. h> –

Pointer – Lecture 8 free • Prototype: void free(void *ptr) #include <stdlib. h> – releases the area pointed to by ptr – ptr must not be null • trying to free the same area twice will generate an error 2 p 2 5 p 1 initial memory 2 p 2 0 1 2 3 4 5 6 7 NULL p 1 free(p 1); Key allocated memory after free 0 1 2 3 4 5 6 Department of Computer Engineering free memory 7 44 Sharif University of Technology

Pointer – Lecture 8 Allocating Memory for a Pointer • There is another way

Pointer – Lecture 8 Allocating Memory for a Pointer • There is another way to allocate memory so the pointer can point to something: #include <stdio. h> #include <stdlib. h> int main(){ int *p; p = (int *) malloc( sizeof(int) ); /* Allocate 4 bytes */ ) scanf("%d", p); printf("%d", *p); //. . free(p); /* This returns the memory to the system*/ /* Important !!! */ } Department of Computer Engineering 45 Sharif University of Technology

Pointer – Lecture 8 Allocating Memory for a Pointer • You can use malloc

Pointer – Lecture 8 Allocating Memory for a Pointer • You can use malloc and free to dynamically allocate and release the memory int *p; p = (int *) malloc(1000 * sizeof(int) ); ) for(i=0; i<1000; i++) p[i] = i; p[999]=3; p[1000]=3; /* Wrong! */ free(p); p[0]=5; /* Wrong! */ Department of Computer Engineering 46 Sharif University of Technology