csc 211 data structures lecture 4

84
1 CSC 211 Data Structures Lecture 4 Dr. Iftikhar Azim Niaz [email protected] 1

Upload: pekelo

Post on 23-Feb-2016

60 views

Category:

Documents


6 download

DESCRIPTION

CSC 211 Data Structures Lecture 4. Dr. Iftikhar Azim Niaz [email protected]. 1. Last Lecture Summary I. Generation of Programming Languages Machine Language Assembly Language High Level Languages Processing a Computer Program Stages of compilation, Interpreter - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: CSC 211 Data Structures Lecture 4

1

CSC 211Data Structures

Lecture 4

Dr. Iftikhar Azim [email protected]

1

Page 2: CSC 211 Data Structures Lecture 4

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

Page 3: CSC 211 Data Structures Lecture 4

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. Entity Employee Attribute Name DOB Sex Designation Value Ahmed 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

Page 4: CSC 211 Data Structures Lecture 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

Page 5: CSC 211 Data Structures Lecture 4

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.

Page 6: CSC 211 Data Structures Lecture 4

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

Page 7: CSC 211 Data Structures Lecture 4

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

Page 8: CSC 211 Data Structures Lecture 4

8

Data types in COnly 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!

Type Size (bytes)char 1int 4short 2long 8float 4double 8

Page 9: CSC 211 Data Structures Lecture 4

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’;char backslash_char = ’\\’;

Page 10: CSC 211 Data Structures Lecture 4

10

Characters are just numbers What does this function do?

charfun(char c){ char new_c;

if ((c >= ’A’) && (c <= ’Z’)) new_c = c - ’A’ + ’a’; else new_c = c;

return (new_c);}

return type

procedure name

argument typeand name

local variabletype and name

Math oncharacters!

comparisonswith characters!

Page 11: CSC 211 Data Structures Lecture 4

11

ArraysArray: a set of pairs (index and value)

data structureFor each index, there is a value associated with that index.

representation (possible)implemented by using consecutive memory.

Page 12: CSC 211 Data Structures Lecture 4

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.

Page 13: CSC 211 Data Structures Lecture 4

13

Arraysscalar: capable of holding a single data itemaggregate variables: capable of holding a collections of values.

Two kinds of aggregates in C:Arrays Structures

An array is a data structure containing a number of data values, all of which have the same typeStatic entity same size throughout program.

Page 14: CSC 211 Data Structures Lecture 4

14

ArraysOne-Dimensional Arrays

The simplest kind of arraysThe 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];

Page 15: CSC 211 Data Structures Lecture 4

15

Arrays Subscripting

Array elements are always numbered starting from 0, so the elements of an array of length nare indexed from 0 to n-1

a[0] a[1] a[8-1]

a[1] = 9;printf(“%d\n”, a[5]);++a[i];

Page 16: CSC 211 Data Structures Lecture 4

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]

-456072

1543-89062-31

645378

c[0]c[1]c[2]c[3]

c[11]c[10]c[9]c[8]c[7]

c[5]c[4]

Page 17: CSC 211 Data Structures Lecture 4

17

Declaring Arrays When declaring arrays, specify

Name Type of array Number of elementsarrayType 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 ];

Page 18: CSC 211 Data Structures Lecture 4

18

Array Declaration and Initializationint 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 } ;

5 2 6 9 3numbers

Page 19: CSC 211 Data Structures Lecture 4

19

Arrays in C

No bounds checking!Allowed – usually causes no errorarray[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)

Page 20: CSC 211 Data Structures Lecture 4

20

Array Representation Homogeneous Each element same size – s bytes

An array of m data values is a sequence of ms bytes Indexing: 0th value at byte s0, 1st value at byte s1, …

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 a[3];

Page 21: CSC 211 Data Structures Lecture 4

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 outputThe third element = 6.

5 2 6 9 3numbers

0 1 2 3 4

Page 22: CSC 211 Data Structures Lecture 4

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!

Page 23: CSC 211 Data Structures Lecture 4

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 ;

Page 24: CSC 211 Data Structures Lecture 4

24

Arrays Array elements are like normal variables

c[ 0 ] = 3;printf( "%d", c[ 0 ] );

Perform operations in subscript. If x equals 3c[ 5 - 2 ] == c[ 3 ] == c[ x ]

Page 25: CSC 211 Data Structures Lecture 4

25

Arrays and For LoopArrays 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];

Page 26: CSC 211 Data Structures Lecture 4

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;

Page 27: CSC 211 Data Structures Lecture 4

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.

Page 28: CSC 211 Data Structures Lecture 4

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

Page 29: CSC 211 Data Structures Lecture 4

29

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

}

Page 30: CSC 211 Data Structures Lecture 4

30

Array subscript may be any integer expressiona[i+j*10]

i = 0; while(i < N) a[i++] = 0;i = 0; while(i < N) a[i] = b[i++];

Page 31: CSC 211 Data Structures Lecture 4

31

Array InitializationAlways 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} */

Page 32: CSC 211 Data Structures Lecture 4

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 itint n[ ] = { 1, 2, 3, 4, 5 };

5 initializers, therefore 5 element array

Page 33: CSC 211 Data Structures Lecture 4

33

Example Using ArraysProblem: 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 UserInstructions

CalculateAverage Score

Page 34: CSC 211 Data Structures Lecture 4

34

Example Using Arrays (con’t) #include <stdio.h> #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 ( ) ;

Page 35: CSC 211 Data Structures Lecture 4

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

Page 36: CSC 211 Data Structures Lecture 4

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 ]++ ; } }

Page 37: CSC 211 Data Structures Lecture 4

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 */

Page 38: CSC 211 Data Structures Lecture 4

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

Page 39: CSC 211 Data Structures Lecture 4

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

Page 40: CSC 211 Data Structures Lecture 4

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.

Page 41: CSC 211 Data Structures Lecture 4

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.

Page 42: CSC 211 Data Structures Lecture 4

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.

Page 43: CSC 211 Data Structures Lecture 4

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.

Page 44: CSC 211 Data Structures Lecture 4

44

Passing an Array to a Function #include <stdio.h>

#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 ] = 0someArray[ 1 ] = 1someArray[ 2 ] = 2someArray[ 3 ] = 3

output

Page 45: CSC 211 Data Structures Lecture 4

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

Processthe Grades

Printthe Results

InitializeGrade Counts

To Zero

Print UserInstructions

CalculateAverage Score

Page 46: CSC 211 Data Structures Lecture 4

46

Grades Program (con’t) #include <stdio.h> #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[ ] ) ;

Page 47: CSC 211 Data Structures Lecture 4

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

Page 48: CSC 211 Data Structures Lecture 4

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

Page 49: CSC 211 Data Structures Lecture 4

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

Page 50: CSC 211 Data Structures Lecture 4

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 ] < MIN) || (anArray [ i ] > MAX) )

{ printf ( “Values must be between %d and %d\n ”, MIN, MAX ) ; printf ( “Enter next value : ” ) ; scanf (“%d “, &anArray[ i ] ) ; } } }

Page 51: CSC 211 Data Structures Lecture 4

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

Page 52: CSC 211 Data Structures Lecture 4

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

Page 53: CSC 211 Data Structures Lecture 4

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

Page 54: CSC 211 Data Structures Lecture 4

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

Page 55: CSC 211 Data Structures Lecture 4

OutlineOutline

1. Initialize array

2. Loop

3. Print

1 /* Fig. 6.8: fig06_08.c

2 Histogram printing program */

3 #include <stdio.h>

4 #define SIZE 10

5

6 int main()

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 }

Page 56: CSC 211 Data Structures Lecture 4

OutlineOutline

Program OutputElement Value Histogram 0 19 ******************* 1 3 *** 2 15 *************** 3 7 ******* 4 11 *********** 5 9 ********* 6 13 ************* 7 5 ***** 8 17 ***************** 9 1 *

Page 57: CSC 211 Data Structures Lecture 4

57

Objects: A set of pairs <index, value> 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 <i, x> has been inserted else return error

The Array ADT

Page 58: CSC 211 Data Structures Lecture 4

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

∙∙∙2n-10 1 2 3 4 5 6 7 8 9 10 11

11

Page 59: CSC 211 Data Structures Lecture 4

59

Memory Addressing

0x00000000

0xFFFFFFFF

address space

program code(text)

static data

heap(dynamically allocated)

stack(dynamically allocated)

PC

SP

These are the addresses

of

memory locations in a 32-

bit machine architecture

Page 60: CSC 211 Data Structures Lecture 4

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)

Page 61: CSC 211 Data Structures Lecture 4

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.

Page 62: CSC 211 Data Structures Lecture 4

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

Page 63: CSC 211 Data Structures Lecture 4

63

Pointer Operations in C Creation& variable Returns variable’s memory

address Dereference* pointer Returns contents stored at

address Indirect assignment

• pointer = valStores value at address• Of course, still have... Assignment

pointer = ptr Stores pointer in another variable

Page 64: CSC 211 Data Structures Lecture 4

64

Using Pointersint 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

Page 65: CSC 211 Data Structures Lecture 4

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?

Page 66: CSC 211 Data Structures Lecture 4

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?

Page 67: CSC 211 Data Structures Lecture 4

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

Page 68: CSC 211 Data Structures Lecture 4

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

Page 69: CSC 211 Data Structures Lecture 4

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

Page 70: CSC 211 Data Structures Lecture 4

70

Pointer Arithmeticpointer + number pointer – number

E.g., pointer + 1 adds 1 something to a pointerchar *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

Page 71: CSC 211 Data Structures Lecture 4

71

The Simplest Pointer in C

Special constant pointer NULL Points to no data Dereferencing illegal – causes segmentation fault

To define, include <stdlib.h> or <stdio.h>

Page 72: CSC 211 Data Structures Lecture 4

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…

Page 73: CSC 211 Data Structures Lecture 4

7373

Pass-by-Referencevoidset_x_and_y(int *x, int *y){ *x = 1001; *y = 1002;}

voidf(void){ int a = 1; int b = 2; set_x_and_y(&a,&b);}

12

a

b

x

y

10011002

Page 74: CSC 211 Data Structures Lecture 4

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;

Page 75: CSC 211 Data Structures Lecture 4

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

Page 76: CSC 211 Data Structures Lecture 4

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

Page 77: CSC 211 Data Structures Lecture 4

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

Page 78: CSC 211 Data Structures Lecture 4

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!

Page 79: CSC 211 Data Structures Lecture 4

79

Exampleswhile ((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];

} elsereturn A[0];

} // getLargest

Page 80: CSC 211 Data Structures Lecture 4

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

Page 81: CSC 211 Data Structures Lecture 4

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!

Page 82: CSC 211 Data Structures Lecture 4

82

Arrays in Cint 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)

Page 83: CSC 211 Data Structures Lecture 4

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]

Page 84: CSC 211 Data Structures Lecture 4

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