Presentation is loading. Please wait.

Presentation is loading. Please wait.

Data Structures – Week #1

Similar presentations


Presentation on theme: "Data Structures – Week #1"— Presentation transcript:

1 Data Structures – Week #1
Introduction

2 Week #1 Contents A Review on C (MM Repr., Operations, Passing to Functions, etc ...) Strings, Arrays Pointers Types of Function Invocation (Call by Value, Call by Reference) 4/14/2019 Fatma Corut Ergin

3 C Program Structure A C program basically has the following form:
Week #1 C Program Structure A C program basically has the following form: Preprocessor Commands Type definitions Function prototypes -- declare function types and variables passed to function. Variables Functions We must have a main() function. A function has the form: type function_name (parameters) { local variables   C Statements   } 4/14/2019 Fatma Corut Ergin

4 Representation of Main Memory
Week #1 Representation of Main Memory 4/14/2019 Fatma Corut Ergin

5 Week #1 Strings A string in C is a sequence of zero or more characters followed by a NULL (\0) character: char className[8]: className = “CSE255” Wrong!! strcpy(className, “CSE225”) C S E 2 5 \0 4/14/2019 Fatma Corut Ergin

6 Functions float findaverage(float a, float b) { float average;
Week #1 Functions float findaverage(float a, float b) { float average;   average=(a+b)/2; return(average); }   main() { float a=5,b=15,result;   result=findaverage(a,b); printf("average=%f n",result); 4/14/2019 Fatma Corut Ergin

7 Arrays Static data structures that
Week #1 Arrays Static data structures that represent contiguous memory locations holding data of same type provide direct access to data they hold have a constant size determined up front (at the beginning of) the run time 4/14/2019 Borahan Tümer, Ph.D.

8 Arrays… cont’d An integer array example in C
Week #1 Arrays… cont’d An integer array example in C int arr[12]; //12 integers 4/14/2019 Borahan Tümer, Ph.D.

9 Multidimensional Arrays
Week #1 Multidimensional Arrays To represent data with multiple dimensions, multidimensional array may be employed. Multidimensional arrays are structures specified with the data value, and as many indices as the dimensions of array Example: int arr2D[r][c]; 4/14/2019 Borahan Tümer, Ph.D.

10 Multidimensional Arrays
Week #1 Multidimensional Arrays m: a two dimensional (2D) array with r rows and c columns Row-major representation: 2D array is implemented row-by-row. Column-major representation: 2D array is implemented column-first. In row-major rep., m[i][j] is the entry of the above matrix m at i+1th row and j+1th column. “i” and “j” are row and column indices, respectively. How many elements? n = r*c elements 4/14/2019 Borahan Tümer, Ph.D.

11 Row-major Implementation
Week #1 Row-major Implementation Question: How can we store the matrix in a 1D array in a row-major fashion or how can we map the 2D array m to a 1D array a? l elements a ... m[0][0] ... m[0][c-1] ... m[r-1][0] ... m[r-1][c-1] ... index: k → k=l+c-1 k=l+(r-1)c+0 k=l+(r-1)c+c-1 k=l In general, m[i][j] is placed at a[k] where k=l+ic+j. 4/14/2019 Borahan Tümer, Ph.D.

12 Implementation Details of Arrays
Week #1 Implementation Details of Arrays Array names are pointers that point to the first byte of the first element of the array. double vect[row_limit];// vect is a pointer!!! Arrays may be efficiently passed to functions using their name and their size where the name specifies the beginning address of the array the size states the bounds of the index values. Arrays can only be copied element by element. 4/14/2019 Borahan Tümer, Ph.D.

13 Implementation Details… cont’d
Week #1 Implementation Details… cont’d #define maxrow …; #define maxcol …; int main() { int minirow; double min; double probability_matrix[maxrow][maxcol]; … ; //probability_matrix initialized!!! min=minrow(probability_matrix, maxrow, maxcol, &minirow); …; return 0; } 4/14/2019 Borahan Tümer, Ph.D.

14 Implementation Details… cont’d
Week #1 Implementation Details… cont’d double minrow(double arr[][maxcol], int xpos, int ypos, int *ind){ // finds minimum of sum of rows of the matrix and returns the sum // and the row index with minimum sum. double min; …; mn = <a large number>; for (i=0; i<=xpos; i++) { sum=0; for (j=0; j<=ypos; j++)‏ sum += darr[i][j]; if (mn > sum) { mn=sum; *ind=i; } // call by reference!!! } return mn; 4/14/2019 Borahan Tümer, Ph.D.

15 Week #1 Records As opposed to arrays in which we keep data of the same type, we keep related data of various types in a record. Records are used to encapsulate (keep together) related data. Records are composite, and hence, user-defined data types. In C, records are formed using the reserved word “struct.” 4/14/2019 Borahan Tümer, Ph.D.

16 Struct We declare as an example a student record called “stdType”.
Week #1 Struct We declare as an example a student record called “stdType”. We declare first the data types required for individual fields of the record stdType, and then the record stdType itself. 4/14/2019 Borahan Tümer, Ph.D.

17 Week #1 Struct… Example enum genderType = {female, male}; // enumerated type declared… typedef enum genderType genderType; // name of enumerated type shortened… struct instrType { … // left for you as exercise!!! } typedef struct instrType instrType; struct classType { // fields (attributes in OOP) of a course declared… char classCode[8]; char className[60]; instrType instructor; struct classType *clsptr; typedef struct classType classType; // name of structure shortened… 4/14/2019 Borahan Tümer, Ph.D.

18 Struct… Example continues
Week #1 Struct… Example continues struct stdType { char id[8]; //key //personal info char name[15]; char surname[25]; genderType gender; //enumerated type … //student info classType current_classes[10]; //...or classType *cur_clsptr classType classes_taken[50]; //...or classType *taken_clsptr float grade; unsigned int credits_earned; … //next record’s first byte’s address struct stdType *sptr; //address of next student record } 4/14/2019 Borahan Tümer, Ph.D.

19 Memory Issues Arrays can be used within records.
Week #1 Memory Issues Arrays can be used within records. Ex: classType current_classes[10]; // from previous slide Each element of an array can be a record. stdType students[1000]; Using an array of classType for keeping taken classes wastes memory space (Why?)‏ Any alternatives? How will we keep student records in MM? In an array? Advantages? Disadvantages? 4/14/2019 Borahan Tümer, Ph.D.

20 Array Representation Advantages
Week #1 Array Representation Advantages Direct access (i.e., faster execution)‏ Disadvantages Not suitable for changing number of student records The higher the extent of memory waste the smaller the number of student records required to store than that at the initial case. The (constant) size of array requires extension which is impossible for static arrays in case the number exceeds the bounds of the array. The other alternative is pointers that provide dynamic memory allocation 4/14/2019 Borahan Tümer, Ph.D.

21 Pointers Pointers are variables that hold memory addresses.
Week #1 Pointers Pointers are variables that hold memory addresses. Declaration of a pointer is based on the type of data of which the pointer holds the memory address. Ex: stdtype *stdptr; 4/14/2019 Borahan Tümer, Ph.D.

22 Week #1 Pointers A pointer is a variable which contains the address in memory of another variable. We can have a pointer to any variable type. The & operator gives the “address of a variable”. The * operator gives the “contents of an object pointed to by a pointer”. int *pointer; 4/14/2019 Fatma Corut Ergin

23 Week #1 Pointers cont. 4/14/2019 Fatma Corut Ergin

24 Week #1 Pointers cont. IMPORTANT: When a pointer is declared it does not point anywhere. You must set it to point somewhere before you use it. int *ip;   *ip = 100; will generate an error (program crash!!) (no compiler error). The correct use is:     int *ip; int x;   ip = &x; *ip = 100; 4/14/2019 Fatma Corut Ergin

25 Linked List Representation
Week #1 Linked List Representation Std #1 Std #2 Std #3 Std #n header Memory heap Std 1 Std 2 Std 3 Std n header Value of header=? Value of header=2E450 4/14/2019 Borahan Tümer, Ph.D.

26 Dynamic Memory Allocation
Week #1 Dynamic Memory Allocation header=(*stdtype) malloc(sizeof(stdtype)); //Copy the info of first student to node pointed to by header s =(*stdtype) malloc(sizeof(stdtype)); //Copy info of second student to node pointed to by header Header->sptr=s; ... 4/14/2019 Borahan Tümer, Ph.D.

27 Arrays and Pointers pa + i (same as) a[i] pa = a (same as) pa = &a[0];
Week #1 Arrays and Pointers int a[10], x; int *pa;   pa = &a[0]; /* pa pointer to address of a[0] */   x = *pa; /* x = contents of pa (a[0] in this case) */ pa + i (same as) a[i] pa = a (same as) pa = &a[0]; &a[i] (same as) a + i pa[i] (same as) *(pa + i) pa = a and pa++ are legal (pointer is a variable) a = pa and a++ are illegal (array is not a variable) 4/14/2019 Fatma Corut Ergin

28 Arrays vs. Pointers Static data structures
Week #1 Arrays vs. Pointers Static data structures Represented by an index and associated value Consecutive memory cells Direct access (+)‏ Constant size (-)‏ Memory not released during runtime (-)‏ Dynamic data structures Represented by a record of information and address of next node Randomly located in heap (cause for need to keep address of next node)‏ Sequential access (-)‏ Flexible size (+)‏ Memory space allocatable and releasable during runtime (+)‏ 4/14/2019 Borahan Tümer, Ph.D.

29 Week #1 Passing to Functions Pointers provide the solution: Pass the address of the variables to the functions and access address of function. void swap(int *px, int *py) { int temp;   temp = *px; /* contents of pointer */   *px = *py; *py = temp; } 4/14/2019 Fatma Corut Ergin

30 Week #1 Common Mistake malloc(): tries to allocate memory dynamically (at run time) and if successful returns a pointer to block of memory requested or a NULL pointer otherwise. What is the mistake in the following piece of code? /* request 100 bytes of memory */ = (char *) malloc(100); *p = ‘y’; p *p 4/14/2019 Fatma Corut Ergin

31 Pointer to Pointer Concept
Week #1 Pointer to Pointer Concept char ch; /* a character */ char *pch; /* a pointer to a character */ char **ppch; /* a pointer to a pointer to a character */ 4/14/2019 Fatma Corut Ergin

32 C Preprocessors #define FALSE 0 #define TRUE !FALSE
Week #1 C Preprocessors #define FALSE 0 #define TRUE !FALSE #define max(A,B) ( (A) > (B) ? (A):(B)) #include <stdio.h> #include “myHeader.h” 4/14/2019 Fatma Corut Ergin

33 Header Files Contains C declarations and macro definitions
Week #1 Header Files Contains C declarations and macro definitions A macro is a fragment of code which has been given a name #define BUFFER_SIZE 1024 foo = (char *) malloc (BUFFER_SIZE); foo = (char *) malloc (1024); Contains declarations for interfaces between the source files of your program 4/14/2019 Fatma Corut Ergin

34 Week #1 Header Files (cont.) Including a header file produces the same results as copying the header file into each source file that needs it. time-consuming error-prone With a header file, the related declarations appear in only one place. if needed, changed in one place, programs that include the header file will automatically use the new version when next recompiled. Eliminates the labor of finding and changing all the copies as well as the risk that a failure to find one copy will result in inconsistencies within a program. 4/14/2019 Fatma Corut Ergin

35 Defined Datatypes .... typedef struct student { char name[50];
Week #1 Defined Datatypes typedef struct student { char name[50]; char surname[50]; int grade; } STUDENT; STUDENT CSE225class[100]; strcpy(CSE225class[0].name, “Fatma”); strcpy(CSE225class[0].surname, “Ergin”); CSE225class[0].grade = 50; .... 4/14/2019 Fatma Corut Ergin

36 File Access FILE *fopen(const char *filename, const char *mode);
Week #1 File Access FILE *fopen(const char *filename, const char *mode); int fclose(FILE *a_file); Windows OS FILE *fp; fp=fopen("c:\\test.txt", “w"); fprintf(fp,"Testing...\n"); fclose(fp); Linux OS fp=fopen(“/tmp/test.txt", “w"); 4/14/2019 Fatma Corut Ergin

37 Function Invocation Call by Value Call by Reference 4/14/2019
Week #1 Function Invocation Call by Value Call by Reference 4/14/2019 Fatma Corut Ergin

38 Call by Value Output: main : i = 1 j = 2 exchange: i = 2 j = 1
Week #1 Call by Value #include <stdio.h> void exchange(int, int); int main(void) { int i = 1, j = 2; printf("main : i = %d j = %d\n", i, j); exchange(i,j); return 0; } void exchange(int i, int j) { int t; t = i, i = j, j = t; printf("exchange: i = %d j = %d\n", i, j); Output: main : i = 1 j = 2 exchange: i = 2 j = 1 main : i = 1 j = 2 4/14/2019 Fatma Corut Ergin

39 Call by Reference Output: main : i = 1 j = 2 exchange: i = 2 j = 1
Week #1 Call by Reference #include <stdio.h> void exchange(int *, int *); int main(void) { int i = 1, j = 2; printf("main : i = %d j = %d\n", i, j); exchange(&i,&j); printf("main : i = %d j = %d\n", i, j); return 0; } void exchange(int *ip, int *jp) { int t; t = *ip, *ip = *jp, *jp = t; printf("exchange: i = %d j = %d\n", *ip, *jp); Output: main : i = 1 j = 2 exchange: i = 2 j = 1 main : i = 2 j = 1 4/14/2019 Fatma Corut Ergin


Download ppt "Data Structures – Week #1"

Similar presentations


Ads by Google