Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 CSC 211 Data Structures Lecture 4 Dr. Iftikhar Azim Niaz 1.

Similar presentations


Presentation on theme: "1 CSC 211 Data Structures Lecture 4 Dr. Iftikhar Azim Niaz 1."— Presentation transcript:

1 1 CSC 211 Data Structures Lecture 4 Dr. Iftikhar Azim Niaz ianiaz@comsats.edu.pk 1

2 2 Last Lecture Summary I Generation of Programming Languages  Machine Language  Assembly Language  High Level Languages Processing a Computer Program  Stages of compilation, Interpreter Procedural and modular programming Structure of a C Program Data and Data structure Abstract Data Type (ADT) 2

3 3 Basic Terms Data  means a value or set of values  34, 10/01/1965, Pascal, (21,25,28,30,35,37,38) Entity  Is one that has certain attributes and which may be assigned values.  EntityEmployee  AttributeName DOBSexDesignation  ValueAhmed 31/12/99 M Director Domain  Set of all possible values that could be assigned to a particular attribute Information is processed data or meaningful data

4 4 Data Type and Data Structure Data Type  defines the specification of a set of data and the characteristics for that data.  is derived from the basic nature of data that are stored for processing rather from their implementation. Data Structure  refers to the actual implementation of the data type and offers a way of storing data in an efficient manner.  Any data structure is designed to organize data to suit a specific purpose so that it can be accessed and worked in appropriate ways both effectively and efficiently  Are implemented using the data types, references and operations on them that are provided by a programming language. 4

5 5 Data Structure Is a particular way of storing and organizing data in a computer so that it can be used efficiently Different kinds of data structures are suited to different kinds of applications and some are highly specialized to specific tasks  e.g. B-trees are particularly well-suited for implementation of databases, while compiler implementations usually use hash tables to look up identifiers provide a means to manage huge amounts of data efficiently, such as large databases and internet indexing services Usually, efficient data structures are a key to designing efficient algorithms.

6 6 Everything is Just a Bunch of Bits Bits can represent many different things  Depends on interpretation You and your program must keep track of what kind of data is at each location in the computer’s memory  E.g., program data types

7 7 Big Picture Processor works with finite-sized data All data implemented as a sequence of bits  Bit = 0 or 1  Represents the level of an electrical charge Byte = 8 bits Word = largest data size handled by processor  32 bits on most older computers  64 bits on most new computers

8 8 Data types in C Only really four basic types:  char  int (short, long, long long, unsigned)  float  double Size of these types Sizes of these types vary from one machine to another! TypeSize (bytes) char1 int4 short2 long8 float4 double8

9 9 Characters (char) Roman alphabet, punctuation, digits, and other symbols:  Can encode within one byte (256 symbols)  ASCII encoding ( man ascii for details) In C: char a_char = ’a’; char newline_char = ’\n’; char tab_char = ’\t’; charbackslash_char = ’\\’;

10 10 Characters are just numbers What does this function do? char fun(char c) { char new_c; if ((c >= ’A’) && (c <= ’Z’)) new_c = c - ’A’ + ’a’; else new_c = c; return (new_c); } return type procedurename argument type and name local variable type and name Math on characters! comparisons with characters!

11 11 Arrays Array: a set of pairs (index and value) data structure For each index, there is a value associated with that index. representation (possible) implemented by using consecutive memory.

12 12 Arrays An array is a group of related data items that all have the same name and the same data type. Arrays can be of any data type we choose. Arrays are static in that they remain the same size throughout program execution. An array’s data items are stored contiguously in memory. Each of the data items is known as an element of the array. Each element can be accessed individually.

13 13 Arrays scalar: capable of holding a single data item aggregate variables: capable of holding a collections of values. Two kinds of aggregates in C: ArraysStructures An array is a data structure containing a number of data values, all of which have the same type Static entitysame size throughout program.

14 14 Arrays One-Dimensional Arrays The simplest kind of arrays The elements, the values of the items, of a one- dimensional array are conceptually arranged one after another in a single row. int a[8]; a #define N 10 …… int a[N];

15 15 Arrays Subscripting Array elements are always numbered starting from 0, so the elements of an array of length n are indexed from 0 to n-1 a[0]a[1] a[8-1] a[1] = 9; printf(“%d\n”, a[5]); ++a[i];

16 16 Arrays Array  Group of consecutive memory locations  Same name and type To refer to an element, specify  Array name  Position number Format: arrayname [ position number ]  First element at position 0  n element array named c : c[ 0 ], c[ 1 ]... c[ n – 1 ] Name of array (Note that all elements of this array have the same name, c) Position number of the element within array c c[6] -45 6 0 72 1543 -89 0 62 -3 1 6453 78 c[0] c[1] c[2] c[3] c[11] c[10] c[9] c[8] c[7] c[5] c[4]

17 17 Declaring Arrays When declaring arrays, specify  Name  Type of array  Number of elements arrayType arrayName[ numberOfElements ];  Examples: int c[ 10 ]; float myArray[ 3284 ]; Declaring multiple arrays of same type  Format similar to regular variables  Example: int b[ 100 ], x[ 27 ];

18 18 Array Declaration and Initialization int numbers[ 5 ] ; The name of this array is “numbers”. This declaration sets aside a chunk of memory that is big enough to hold 5 integers. It does not initialize those memory locations to 0 or any other value. They contain garbage. Initializing an array may be done with an array initialization, as in : int numbers[ 5 ] = { 5, 2, 6, 9, 3 } ; 52693 numbers

19 19 Arrays in C No bounds checking! Allowed – usually causes no error array[10] may overwrite b Unlike Java, array size in declaration int array[10]; int b; array[0] = 3; array[9] = 4; array[10] = 5; array[-1] = 6; Compare: C: int array[10]; Java: int[] array = new int[10]; All elements of same type – homogenous First element (index 0) Last element (index size - 1)

20 20 Array Representation Homogeneous  Each element same size – s bytes  An array of m data values is a sequence of m  s bytes  Indexing: 0 th value at byte s  0, 1 st value at byte s  1, … m and s are not part of representation  Unlike in some other languages  s known by compiler – usually irrelevant to programmer  m often known by compiler – if not, must be saved by programmer a[0] a[1] a[2] 0x1000 0x1004 0x1008 int ]; int a[3];

21 21 Accessing Array Elements Each element in an array has a subscript (index) associated with it. Subscripts are integers and always begin at zero. Values of individual elements can be accessed by indexing into the array. For example, printf(“The third element = %d.\n”, numbers[ 2 ] ) ; would give the output The third element = 6. 52693 numbers 0 1 2 3 4

22 22 Accessing Array Elements (con’t) A subscript can also be an expression that evaluates to an integer. numbers[ (a + b) * 2 ] ; Caution! It is a logical error when a subscript evaluates to a value that is out of range for the particular array. Some systems will handle an out-of-range error gracefully and some will not (including ours). Normally, when you see a file named core (or core*) it means you exceeded the end of an array!

23 23 Modifying Elements Individual elements of an array can also be modified using subscripts. numbers[ 4 ] = 20 ; /*changes the value of the element found at subscript 4 to 20 */ Initial values may be stored in an array using indexing, rather than using an array initialization. numbers[ 0 ] = 5 ; numbers[ 1 ] = 2 ; numbers[ 2 ] = 6 ; numbers[ 3 ] = 9 ; numbers[ 4 ] = 3 ;

24 24 Arrays Array elements are like normal variables c[ 0 ] = 3; printf( "%d", c[ 0 ] );  Perform operations in subscript. If x equals 3 c[ 5 - 2 ] == c[ 3 ] == c[ x ]

25 25 Arrays and For Loop Arrays and for loops go hand-in-hand Idioms: for(i = 0; i < N; i++) a[i] = 0; for(i = 0; i < N; i++) scanf(“%d”, &a[i]); for(i = 0; i < N; i++) sum += a[i];

26 26 Array and its Indexing C doesn’t require that subscript bounds be checked. If a subscript goes out of range, the program’s behavior is undefined. int a[10], i; for(i = 1; i <= 10; i++) a[i] = 0;

27 27 Filling Large Arrays Since many arrays are quite large, using an array initialization can be impractical. Large arrays are often filled using a for loop. for ( i = 0; i < 100; i++ ) { values [ i ] = 0 ; } would set every element of the 100 element array “values” to 0.

28 28 More Declarations int score [ 39 ], gradeCount [ 5 ]; Declares two arrays of type int. Neither array has been initialized. “score” contains 39 elements (one for each student in a class). “gradeCount” contains 5 elements (one for each possible grade, A - F).

29 29 Using #define for Array Sizes #define SIZE 39 #define GRADES 5 int main ( void ) { int score [ SIZE ] ; int gradeCount [ GRADES ] ;  }

30 30 Array subscript may be any integer expression a[i+j*10] i = 0; while(i < N) a[i++] = 0; i = 0; while(i < N) a[i] = b[i++];

31 31 Array Initialization Always initialize array when you declare it int a[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int a[10] = {1, 2, 3, 4, 5, 6}; /* {1, 2, 3, 4, 5, 0, 0, 0, 0, 0} */ int a[10] = {0}; /* {0, 0, 0, 0, 0, 0, 0, 0, 0, 0} */ int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; /* {0, 0, 0, 0, 0, 0, 0, 0, 0, 0} */

32 32 Examples Using Arrays Initializers int n[ 5 ] = { 1, 2, 3, 4, 5 };  If not enough initializers, rightmost elements become 0 int n[ 5 ] = { 0 } All elements 0  If too many a syntax error is produced syntax error  C arrays have no bounds checking If size omitted, initializers determine it int n[ ] = { 1, 2, 3, 4, 5 };  5 initializers, therefore 5 element array

33 33 Example Using Arrays Problem: Find the average test score and the number of A’s, B’s, C’s, D’s, and F’s for a particular class. Design: Main Print User InstructionsCalculate Average Score

34 34 Example Using Arrays (con’t) #include #define SIZE 39 /* number of tests */ #define GRADES 5 /* number of different grades: A, B, C, D, F */ void printInstructions ( void ) ; double findAverage ( double sum, int quantity ) ; int main ( void ) { int i ; /* loop counter */ int total ; /* total of all scores */ int score [ SIZE ] ; /* student scores */ int gradeCount [ GRADES ] ; /* count of A’s, B’s, C’s, D’s, F’s */ double average ; /* average score */ /* Print the instructions for the user */ printInstructions ( ) ;

35 35 Example Using Arrays (con’t) /* Initialize grade counts to zero */ for ( i = 0; i < GRADES; i++ ) { gradeCount [ i ] = 0 ; } /* Fill score array with scores */ for ( i = 0; i < SIZE; i++ ) { printf (“Enter next score: ”) ; scanf (“%d “, &score [ i ] ) ; }

36 36 Example Using Arrays (con’t) /* Calculate score total and count number of each grade */ for ( i = 0; i < SIZE; i++ ) { total += score [ i ] ; switch ( score [ i ] / 10 ) { case 10 : case 9 : gradeCount [ 4 ]++ ; break ; case 8 : gradeCount [ 3 ]++ ; break ; case 7 : gradeCount [ 2 ]++ ; break ; case 6 : gradeCount [ 1 ]++ ; break ; default : gradeCount [ 0 ]++ ; }

37 37 Example Using Arrays (con’t) /* Calculate the average score */ average = findAverage ( total, SIZE ) ; /* Print the results */ printf (“The class average is %.2f\n”, average ) ; printf (“There were %2d As\n”, gradeCount [ 4 ] ) ; printf (“ %2d Bs\n”, gradeCount [ 3 ] ) ; printf (“ %2d Cs\n”, gradeCount [ 2 ] ) ; printf (“ %2d Ds\n”, gradeCount [ 1 ] ) ; printf (“ %2d Fs\n”, gradeCount [ 0 ] ) ; return 0 ; } /* end main */

38 38 Example Using Arrays (con’t) /***************************************************************** ** printInstructions - prints the user instructions ** Inputs: None ** Outputs: None /***************************************************************** void printInstructions ( void ) { printf (“This program calculates the average score\n”) ; printf (“for a class of 39 students. It also reports the\n”) ; printf (“number of A’s, B’s, C’s, D’s, and F’s. You will\n”) ; printf (“be asked to enter the individual scores.\n”) ; }

39 39 Example Using Arrays (con’t) /*************************************************************** ** findAverage - calculates an average ** Inputs: sum - the sum of all values ** num - the number of values ** Outputs: the computed average ****************************************************************/ double findAverage ( double sum, int num ) { double average ; /* computed average */ if ( num != 0 ) { average = sum / num ; } else { average = 0 ; } return average ; }

40 40 Indexing Arrays As long as we know – the beginning location of an array, – the data type being held in the array, and – the size of the array (so that we don’t go out of range), then we can access or modify any of its elements using indexing. The array name alone (without [ ] ) is just a variable that contains the starting address of the block of memory where the array is held.

41 41 Call (Pass) by Value So far, we have passed only values to functions. The function has a local variable (a formal parameter) to hold its own copy of the value passed in. When we make changes to this copy, the original (the corresponding actual parameter) remains unchanged. This is known as calling (passing) by value.

42 42 Passing Arrays to Functions The function prototype: void fillArray ( int ages[ ], int numElements ); The function definition header: void fillArray ( int ages[ ], int numElements ) The function call: fillArray ( ages, SIZE ); Notice that we are passing only the name of the array (the address) and that we aren’t returning anything (the function is void) because we will be modifying the original array from within the function.

43 43 Call (Pass) by Reference As demonstrated with arrays, we can pass addresses to functions. This is known as calling (passing) by reference. When the function is passed an address, it can make changes to the original (the corresponding actual parameter). There is no copy made. This is great for arrays, because arrays are usually very large. We really don’t want to make a copy of an array. It would use too much memory.

44 44 Passing an Array to a Function #include #define SIZE 4 void fillArray ( int intArray[ ], int size ) ; int main ( void ) { int someArray [ SIZE ] ; fillArray ( someArray, SIZE ) ; /* Print the elements of the array */ for ( i = 0; i < SIZE; i++ ) { printf (someArray[ %d ] = %d\n”, i, someArray[ i ] ) ; } return 0 ; } /******************************************* fillArray is a function that will fill each element of any integer array passed to it with a value that is the same as that element’s subscript. *******************************************/ void fillArray ( int anArray[ ], int numElements ) { int i ; for ( i = 0; i < numElements; i++ ) { anArray [ i ] = i ; } someArray[ 0 ] = 0 someArray[ 1 ] = 1 someArray[ 2 ] = 2 someArray[ 3 ] = 3 output

45 45 Grades Program Using Pass by Reference Problem: Find the average test score and the number of A’s, B’s, C’s, D’s, and F’s for a particular class. New Design: Main Read Grades GradesProcess the Grades Print the Results Initialize Grade Counts To Zero Print User Instructions Calculate Average Score

46 46 Grades Program (con’t) #include #define SIZE 39 #define GRADES 5 #define A 4 #define B 3 #define C 2 #define D 1 #define F 0 #define MAX 100 #define MIN 0 void printInstructions ( ) ; void initArray ( int anArray[ ], int size ) ; void fillArray ( int anArray[ ], int size ) ; double processGrades (int score[ ], int size, int gradeCount[ ] ) ; double findAverage ( double sum, int num ) ; void printResults ( double average, int gradeCount[ ] ) ;

47 47 Grades Program (con’t) int main ( void ) { int score [ SIZE ]; /* student scores */ int gradeCount [ GRADES ] ; /* count of A’s, B’s, C’s, D’s, F’s */ double average; /* average score */ printInstructions ( ) ; initArray ( gradeCount, GRADES ) ; fillArray (score, SIZE ) ; average = processGrades (score, SIZE, gradeCount ) ; printResults (average, gradeCount) ; return 0 ; }

48 48 Grades Program (con’t) /***************************************************************** ** printInstructions - prints the user instructions ** Inputs: None ** Outputs: None /***************************************************************** void printInstructions ( ) { printf (“This program calculates the average score\n”) ; printf (“for a class of 39 students. It also reports the\n”) ; printf (“number of A’s, B’s, C’s, D’s, and F’s. You will\n”) ; printf (“be asked to enter the individual scores.\n”) ; }

49 49 Grades Program (con’t) /******************************************************************* /* initArray - initializes an integer array to all zeros /* Inputs: anArray - array to be initialized /* size - size of the array /* Outputs: None /******************************************************************/ void initArray ( int anArray [ ], int size ) { for ( i = 0; i < size; i++ ) { anArray [ i ] = 0 ; }

50 50 Grades Program (con’t) /**************************************************************************************** ** fillArray - fills an integer array with valid values that are entered by the user. ** Assures the values are between MIN and MAX. ** Inputs: anArray - array to fill ** Outputs: size - size of the array ** Side Effect - MIN and MAX must be #defined in this file ****************************************************************************************/ void fillArray ( int anArray [ ], int size ) { int i ; /* loop counter */ for ( i = 0; i < size; i++ ) { printf (“Enter next value : ”) ; scanf (“%d “, &anArray [ i ] ) ; while ( (anArray [ i ] MAX) ) { printf ( “Values must be between %d and %d\n ”, MIN, MAX ) ; printf ( “Enter next value : ” ) ; scanf (“%d “, &anArray[ i ] ) ; }

51 51 Grades Program (con’t) /******************************************************************************** ** processGrades - counts the number of A’s, B’s, C’s, D’s, and F’s, and ** computes the average score ** Inputs: score - array of student scores size - size of the array gradeCount - grade counts all initialized to zero ** Outputs: gradeCount - number of A’s, B’s, C’s, D’s, and F’s ** Side Effect: A, B, C, D, and F must be #defined in this file *********************************************************************************/ double ProcessGrades (int score [ ], int size, int gradeCount [ ] ) { int total = 0; /* total of all scores */ double average; /* average score */ for ( i = 0 ; i < size ; i++) { total += score [ i ] ;

52 52 Grades Program (con’t) switch ( score [ i ] / 10 ) { case 10 : case 9 : gradeCount [ A ]++ ; break ; case 8 : gradeCount [ B ]++ ; break ; case 7 : gradeCount [ C ]++ ; break ; case 6 : gradeCount [ D ]++ ; break ; case 5 : case 4 : case 3 : case 2 : case 1 : case 0: gradeCount [ F ]++ ; break ; default : printf (“Error in score.\n”) ; } average = findAverage ( total, size ) ; return average ; }

53 53 Grades Program (con’t) /*************************************************************** ** findAverage - calculates an average ** Inputs: sum - the sum of all values ** num - the number of values ** Outputs: the computed average ****************************************************************/ double findAverage ( double sum, int num ) { double average ; /* computed average */ if ( num != 0 ) { average = sum / num ; } else { average = 0 ; } return average ; }

54 54 Grades Program (con’t) /*********************************************************************************** ** printResults - prints the class average and the grade distribution for ** the class. ** Inputs: average - class average ** gradeCount - number of A’s, B’s, C’s, D’s, and F’s ** Outputs: None ** Side Effect: A, B, C, D, and F must be #defined in this file /***********************************************************************************/ void printResults (double average, int gradeCount [ ] ) { printf (“The class average is %.2f\n”, average ) ; printf (“There were %2d As\n”, gradeCount [ A ] ) ; printf (“ %2d Bs\n”, gradeCount [ B ] ) ; printf (“ %2d Cs\n”, gradeCount [ C ] ) ; printf (“ %2d Ds\n”, gradeCount [ D ] ) ; printf (“ %2d Fs\n”, gradeCount [ F ] ) ; }

55 Outline 1. Initialize array 2. Loop 3. Print 1/* Fig. 6.8: fig06_08.c 2 Histogram printing program */ 3#include 4#define SIZE 10 5 6int main() 7{7{ 8 int n[ SIZE ] = { 19, 3, 15, 7, 11, 9, 13, 5, 17, 1 }; 9 int i, j; 10 11 printf( "%s%13s%17s\n", "Element", "Value", "Histogram" ); 12 13 for ( i = 0; i <= SIZE - 1; i++ ) { 14 printf( "%7d%13d ", i, n[ i ]) ; 15 16 for ( j = 1; j <= n[ i ]; j++ ) /* print one bar */ 17 printf( "%c", '*' ); 18 19 printf( "\n" ); 20 } 21 22 return 0; 23}

56 Outline Program Output Element Value Histogram 0 19 ******************* 1 3 *** 2 15 *************** 3 7 ******* 4 11 *********** 5 9 ********* 6 13 ************* 7 5 ***** 8 17 ***************** 9 1 *

57 57 Objects: A set of pairs where for each value of index there is a value from the set item. Index is a finite ordered set of one or more dimensions, for example, {0, …, n-1} for one dimension, {(0,0),(0,1),(0,2),(1,0),(1,1),(1,2),(2,0),(2,1),(2,2)} for two dimensions, etc. Methods: for all A  Array, i  index, x  item, j, size  integer Array Create(j, list) ::= return an array of j dimensions where list is a j-tuple whose kth element is the size of the kth dimension. Items are undefined. Item Retrieve(A, i) ::= if (i  index) return the item associated with index value i in array A else return error Array Store(A, i, x) ::= if (i in index) return an array that is identical to array A except the new pair has been inserted else return error The Array ADT

58 58 Definition – Pointer A value indicating the number of (the first byte of) a data object  Also called an Address or a Location Used in machine language to identify which data to access E.g., stack pointer is address of most recent entry of The Stack Usually 2, 4, or 8 bytes, depending upon machine architecture∙∙∙ 2 n -1 01234567891011 11

59 59 Memory Addressing 0x000000000xFFFFFFFF address space program code (text) static data heap (dynamically allocated) stack PC SP These are the addresses of memory locations in a 32- bit machine architecture

60 60 Pointers in C Used everywhere  For building useful, interesting, data structures  For returning data from functions  For managing arrays '&' unary operator generates a pointer to x  E.g., scanf("%d", &x);  E.g., p = &c;  Operand of '&' must be an l-value — i.e., a legal object on left of assignment operator ( '=' ) Unary '*' operator dereferences a pointer  i.e., gets value pointed to  E.g. *p refers to value of c (above)  E.g., *p = x + y; *p = *q; Not the same as binary '&' operator (bitwise AND)

61 61 Declaring Pointers in C int *p; — a pointer to an int double *q; — a pointer to a double char **r; — a pointer to a pointer to a char type *s; — a pointer to an object of type type E.g, a struct, union, function, something defined by a typedef, etc.

62 62 Declaring Pointers in C (continued) Pointer declarations:–read from right to left const int *p; p is a pointer to an integer constant I.e., pointer can change, thing it points to cannot int * const q; q is a constant pointer to an integer variable I.e., pointer cannot change, thing it points to can! const int * const r; r is a constant pointer to an integer constant

63 63 Pointer Operations in C Creation & variableReturns variable’s memory address Dereference * pointerReturns contents stored at address Indirect assignment pointer = valStores value at address Of course, still have... Assignment pointer = ptrStores pointer in another variable

64 64 Using Pointers int i1; int i2; int *ptr1; int *ptr2; i1 = 1; i2 = 2; ptr1 = &i1; ptr2 = ptr1; *ptr1 = 3; i2 = *ptr2; i1: i2: ptr1: 0x1000 0x1004 0x1008 … ptr2: … 0x100C 0x1010 0x1014 1 2 0x1000 0x1000 3 3

65 65 Using Pointers (cont.) Type check warning: int_ptr2 is not an int int1 becomes 8 int int1 = 1036; /* some data to point to */ int int2 = 8; int *int_ptr1 = &int1; /* get addresses of data */ int *int_ptr2 = &int2; *int_ptr1 = int_ptr2; *int_ptr1 = int2; What happens?

66 66 Using Pointers (cont.) Type check warning: *int_ptr2 is not an int * Changes int_ptr1 – doesn’t change int1 int int1 = 1036; /* some data to point to */ int int2 = 8; int *int_ptr1 = &int1; /* get addresses of data */ int *int_ptr2 = &int2; int_ptr1 = *int_ptr2; int_ptr1 = int_ptr2; What happens?

67 67 Pointer Arithmetic int *p, *q; q = p + 1;  Construct a pointer to the next integer after *p and assign it to q double *p, *r; int n; r = p + n;  Construct a pointer to a double that is n doubles beyond *p, and assign it to r  n may be negative

68 68 Pointer Arithmetic (continued) long int *p, *q; p++; q--;  Increment p to point to the next long int ; decrement q to point to the previous long int float *p, *q; int n; n = p – q;  n is the number of floats between *p and *q ; i.e., what would be added to q to get p

69 69 Pointer Arithmetic (continued) long int *p, *q; p++; q--;  Increment p to point to the next long int ; decrement q to point to the previous long int float *p, *q; int n; n = p – q;  n is the number of floats between *p and *q ; i.e., what would be added to q to get p C never checks that the resulting pointer is valid

70 70 Pointer Arithmetic pointer + numberpointer – number E.g., pointer + 1 adds 1 something to a pointer char *p; char a; char b; p = &a; p += 1; int *p; int a; int b; p = &a; p += 1; In each, p now points to b (Assuming compiler doesn’t reorder variables in memory) Adds 1*sizeof(char) to the memory address Adds 1*sizeof(int) to the memory address Pointer arithmetic should be used cautiously

71 71 The Simplest Pointer in C Special constant pointer NULL  Points to no data  Dereferencing illegal – causes segmentation fault  To define, include or

72 72 Generic Pointers void *: a “pointer to anything” Lose all information about what type of thing is pointed to  Reduces effectiveness of compiler’s type-checking  Can’t use pointer arithmetic void *p; int i; char c; p = &i; p = &c; putchar(*(char *)p); type cast: tells the compiler to “change” an object’s type (for type checking purposes – does not modify the object in any way) Dangerous! Sometimes necessary…

73 73 73 Pass-by-Reference void set_x_and_y(int *x, int *y) int *y){ *x = 1001; *x = 1001; *y = 1002; *y = 1002;}voidf(void){ int a = 1; int a = 1; int b = 2; int b = 2; set_x_and_y(&a,&b); set_x_and_y(&a,&b);} 1 2 a b x y 1001 1002

74 74 Arrays and Pointers Arrays and pointers are closely related in C  In fact, they are essentially the same thing!  Esp. when used as parameters of functions int A[10]; int *p;  Type of A is int *  p = A; and A = p; are legal assignments  *p refers to A[0] *(p + n) refers to A[n]  p = &A[5]; is the same as p = A + 5;

75 75 Arrays and Pointers (continued) double A[10]; vs. double *A; Only difference:–  double A[10] sets aside ten units of memory, each large enough to hold a double  double *A sets aside one pointer-sized unit of memory You are expected to come up with the memory elsewhere!  Note:– all pointer variables are the same size in any given machine architecture Regardless of what types they point to

76 76 Note C does not assign arrays to each other E.g,  double A[10]; double B[10]; A = B; assigns the pointer value B to the pointer value A Contents of array A are untouched

77 77 Arrays as Function Parameters void init(float A[], int arraySize); void init(float *A, int arraySize); Are identical function prototypes! Pointer is passed by value I.e. caller copies the value of a pointer to float into the parameter A Called function can reference through that pointer to reach thing pointed to

78 78 Arrays as Function Parameters (continued) void init(float A[], int arraySize){ int n; for(n = 0; n < arraySize; n++) A[n] = (float)n; }//init Assigns values to the array A in place  So that caller can see the changes!

79 79 Examples while ((rc = scanf("%lf", &array[count])) !=EOF && rc==0) … double getLargest(const double A[], const int sizeA) { double d; if (sizeA > 0) { d = getLargest(&A[1], sizeA-1); return (d > A[0]) ? d : A[0]; } else return A[0]; }// getLargest

80 80 Result Even though all arguments are passed by value to functions … … pointers allow functions to assign back to data of caller Arrays are pointers passed by value

81 81 Safety Note When passing arrays to functions, always specify const if you don’t want function changing the value of any elements Reason:– you don’t know whether your function would pass array to another before returning to you Exception – many software packages don’t specify const in their own headers, so you can’t either!

82 82 Arrays in C int list[5], *plist[5]; list[5]: five integers list[0], list[1], list[2], list[3], list[4] *plist[5]: five pointers to integers plist[0], plist[1], plist[2], plist[3], plist[4] implementation of 1-D array list[0]base address =  list[1]  + sizeof(int) list[2]  + 2*sizeof(int) list[3]  + 3*sizeof(int) list[4]  + 4*size(int)

83 83 Arrays in C (cont’d) Compare int *list1 and int list2[5] in C. Same:list1 and list2 are pointers. Difference:list2 reserves five locations. Notations: list2 - a pointer to list2[0] (list2 + i) - a pointer to list2[i] (&list2[i]) *(list2 + i) - list2[i]

84 84 Summary Data type and Data structure Data types in C Arrays  Declaration  Initialization  Representation  Operations  Arrays and functions Pointers  Declaration, Initialization  Arrays and pointers


Download ppt "1 CSC 211 Data Structures Lecture 4 Dr. Iftikhar Azim Niaz 1."

Similar presentations


Ads by Google