C programming Language Chapter 4 Arrays and Strings


![Array Definition int ages[10]; Elements type Array name Number of elements Name of the Array Definition int ages[10]; Elements type Array name Number of elements Name of the](https://slidetodoc.com/presentation_image_h2/ac5cd42c1655a60ed6382e5ecd0daadd/image-3.jpg)

![Array Subscripting Operator [] 100 104 108 112 116 120 124 128 132 136 Array Subscripting Operator [] 100 104 108 112 116 120 124 128 132 136](https://slidetodoc.com/presentation_image_h2/ac5cd42c1655a60ed6382e5ecd0daadd/image-5.jpg)
![Array Subscripting Operator [] What happens when accessing the 10’th place of ages: ages[10] Array Subscripting Operator [] What happens when accessing the 10’th place of ages: ages[10]](https://slidetodoc.com/presentation_image_h2/ac5cd42c1655a60ed6382e5ecd0daadd/image-6.jpg)

![Array Initialization n Within declaration (using an initialization list): int array[5] = {5, 8, Array Initialization n Within declaration (using an initialization list): int array[5] = {5, 8,](https://slidetodoc.com/presentation_image_h2/ac5cd42c1655a60ed6382e5ecd0daadd/image-8.jpg)
![Example Reverse an array: #define SIZE 5 int array[SIZE]={1, 2, 3, 4}, temp, i, Example Reverse an array: #define SIZE 5 int array[SIZE]={1, 2, 3, 4}, temp, i,](https://slidetodoc.com/presentation_image_h2/ac5cd42c1655a60ed6382e5ecd0daadd/image-9.jpg)











![Two-dimensional Array Example int matrix[3][4]; matrix[0][0]: Line: 0 Column: 0 What is the address Two-dimensional Array Example int matrix[3][4]; matrix[0][0]: Line: 0 Column: 0 What is the address](https://slidetodoc.com/presentation_image_h2/ac5cd42c1655a60ed6382e5ecd0daadd/image-21.jpg)



![String Definition n String definition: n char name[10]; Name consists of 10 chars. But String Definition n String definition: n char name[10]; Name consists of 10 chars. But](https://slidetodoc.com/presentation_image_h2/ac5cd42c1655a60ed6382e5ecd0daadd/image-25.jpg)
![String Initialization char name[13] = “Im a donkey”; I m a d o n String Initialization char name[13] = “Im a donkey”; I m a d o n](https://slidetodoc.com/presentation_image_h2/ac5cd42c1655a60ed6382e5ecd0daadd/image-26.jpg)
![String Initialization char name[13] = “Im a donkey”; Comment: The assignment is permitted only String Initialization char name[13] = “Im a donkey”; Comment: The assignment is permitted only](https://slidetodoc.com/presentation_image_h2/ac5cd42c1655a60ed6382e5ecd0daadd/image-27.jpg)

![String Library n int strcmp(char str 1[], char str 2[]) Compares two strings (lexicographically); String Library n int strcmp(char str 1[], char str 2[]) Compares two strings (lexicographically);](https://slidetodoc.com/presentation_image_h2/ac5cd42c1655a60ed6382e5ecd0daadd/image-29.jpg)
![String Library n int strcmp(char str 1[], char str 2[]) Compares two strings (lexicographically); String Library n int strcmp(char str 1[], char str 2[]) Compares two strings (lexicographically);](https://slidetodoc.com/presentation_image_h2/ac5cd42c1655a60ed6382e5ecd0daadd/image-30.jpg)
![String Library n char *strcat(char str 1[], char str 2[]) Concatenating str 2 to String Library n char *strcat(char str 1[], char str 2[]) Concatenating str 2 to](https://slidetodoc.com/presentation_image_h2/ac5cd42c1655a60ed6382e5ecd0daadd/image-31.jpg)
![String Library n char *strcat(char str 1[], char str 2[]) Concatenating str 2 to String Library n char *strcat(char str 1[], char str 2[]) Concatenating str 2 to](https://slidetodoc.com/presentation_image_h2/ac5cd42c1655a60ed6382e5ecd0daadd/image-32.jpg)
![String Library n char *strcat(char str 1[], char str 2[]) Concatenating str 2 to String Library n char *strcat(char str 1[], char str 2[]) Concatenating str 2 to](https://slidetodoc.com/presentation_image_h2/ac5cd42c1655a60ed6382e5ecd0daadd/image-33.jpg)



![Array as Parameter – Stack: Example initialize gets arr, size and arr[0]. It assigns Array as Parameter – Stack: Example initialize gets arr, size and arr[0]. It assigns](https://slidetodoc.com/presentation_image_h2/ac5cd42c1655a60ed6382e5ecd0daadd/image-37.jpg)








![2 D-array as Parameter n So note the correct declaration now. void func(int mat[][4]); 2 D-array as Parameter n So note the correct declaration now. void func(int mat[][4]);](https://slidetodoc.com/presentation_image_h2/ac5cd42c1655a60ed6382e5ecd0daadd/image-46.jpg)
- Slides: 46
C programming Language Chapter 4: Arrays and Strings ספטמבר 04 Copyright Meir Kalech 1
Array Structure n Assume a C program stores the ages of 3 children. Which variables should we define? Very good! n n But defining 3 variables is petty easy. Let’s think about say 10 children (to be continued ), so should the programmer define 10 variables, or more…? ? ? An array can better solve this problem by defining multiple similar variables using a single definition. The definition contains: type, name and number of requested elements. All the variables will be created sequentially in the memory. ספטמבר 04 Copyright Meir Kalech 2
Array Definition int ages[10]; Elements type Array name Number of elements Name of the array = First address of the array address 100 104 108 112 116 120 124 128 value ? ? ? 0 1 2 3 4 5 6 7 8 9 index ספטמבר 04 Copyright Meir Kalech 132 136 3
Array Definition n sizeof() operator gets a type or variable and returns its size in bytes. n n // print 4 Array subscripting operator [] denotes an index in an array and enables access to the value of the addressed array index. n n For example: int x; printf(“%d”, sizeof(int)); printf(“%d”, sizeof(x)); For example: int ages[10]; ages[3] = 23; printf(“%d”, ages[3]); What is sizeof(ages)? ספטמבר 04 // definition 4 * 10 = 40 // access Copyright Meir Kalech 4
Array Subscripting Operator [] 100 104 108 112 116 120 124 128 132 136 ? ? ? 23 ? ? ? 0 1 2 3 4 5 6 7 8 9 ages[3] ages[5] Explanation: “ages” is the first address of the array (100). ages[3]: ages+3*sizeof(int) We get the address of the fourth element. Then operator [] accesses the value of that address. ספטמבר 04 Copyright Meir Kalech 5
Array Subscripting Operator [] What happens when accessing the 10’th place of ages: ages[10] = 30 ? ? ? 100 104 108 112 116 120 124 128 132 136 140 ? ? ? 23 ? ? 0 1 2 3 4 5 6 7 8 9 10 ages[10] DANGEROUS!!! Be careful!!! This address is not allocated to your program ספטמבר 04 Copyright Meir Kalech 6
Notes on Arrays No boundary checks are performed by the computer. n Size (number of elements) must be constant – requested amount of memory must be known at compilation time: int i = 5; int array[i]; // wrong, i is not a constant! However: #define SIZE 5 int array[SIZE]; // OK, SIZE is a symbolic constant! n n C does not have any operator to work with an array “as a whole”: n n For instance: we can’t assign into an array multiple values at once; we can’t print all the array at once, etc… 100 question: what is the output of - printf(“%p”, ages); ספטמבר 04 Copyright Meir Kalech 7
Array Initialization n Within declaration (using an initialization list): int array[5] = {5, 8, 2, 7}; 5 8 2 7 0 0 1 2 3 4 Automatically initialized to 0 If the size of array is not specified, size is determined by the number of initializing values provided: int array[] = {5, 8, 2, 7}; 5 8 2 7 0 1 2 3 Looping through the elements and assigning them a value: int array[5], i; for (i = 0; i < 5; ++i) array[i] = i; // or scanf(“%d”, &array[i]); ספטמבר 04 Copyright Meir Kalech 8
Example Reverse an array: #define SIZE 5 int array[SIZE]={1, 2, 3, 4}, temp, i, j; for (i=0, j=SIZE-1; i<j; i++, j--) { temp = array[i]; array[i] = array[j]; array[j] = temp; } 1 2 3 4 0 0 1 2 3 4 ספטמבר 04 Copyright Meir Kalech Array initialization 9
Example n First iteration: 1 2 3 4 0 0 1 2 3 4 i=0 ספטמבר 04 temp j=4 Copyright Meir Kalech 10
Example n First iteration: 1 2 3 4 0 0 1 2 3 4 i=0 ספטמבר 04 j=4 Copyright Meir Kalech 1 temp = array[i]; 11
Example n First iteration: 0 2 3 4 0 0 1 2 3 4 i=0 1 temp j=4 array[i] = array[j]; ספטמבר 04 Copyright Meir Kalech 12
Example n First iteration: 0 2 3 4 1 0 1 2 3 4 i=0 1 temp j=4 array[j] = temp; ספטמבר 04 Copyright Meir Kalech 13
Example n First iteration: 0 2 3 4 1 0 1 2 3 4 i=1 1 temp j=3 i++, j-- ספטמבר 04 Copyright Meir Kalech 14
Example n Second iteration: 0 2 3 4 1 0 1 2 3 4 i=1 ספטמבר 04 j=3 Copyright Meir Kalech 2 temp = array[i]; 15
Example n Second iteration: 0 4 3 4 1 0 1 2 3 4 i=1 2 temp j=3 array[i] = array[j]; ספטמבר 04 Copyright Meir Kalech 16
Example n Second iteration: 0 4 3 2 1 0 1 2 3 4 i=1 2 temp j=3 array[j] = temp; ספטמבר 04 Copyright Meir Kalech 17
Example n Second iteration: 0 4 3 2 1 0 1 2 3 4 i=2 2 temp j=2 i++, j-i is not smaller than j so STOP!!! ספטמבר 04 Copyright Meir Kalech 18
Two-dimensional Array n n Two-dimensional (2 D) array is an array of arrays. For instance: n n n the definition int matrix[3][4] means 3 arrays of 4 integers each. As for a one-dimensional (1 D) array, the elements will be created sequentially in memory (in row-major order). 100 104 108 112 116 120 124 128 132 136 140 144 ? ? ? 0 1 2 3 4 5 6 7 8 9 10 11 So what is the difference between the two? ? ? ספטמבר 04 Copyright Meir Kalech 19
Two-dimensional Array n n n The difference is in the way of access to the elements. Single operator [] is used for access to elements in a one-dimensional array. Double operator [][] (not [ , ]) is used for access to a two-dimensional array: n n n The first [] locates the requested array (the line). The second [] locates the requested element in the line array (the column). Conclusion: n n physically: one-dimensional and multi-dimensional arrays are the same. Logically: one-dimensional is used as a single list of elements while two-dimensional is used as a multi-list of elements. ספטמבר 04 Copyright Meir Kalech 20
Two-dimensional Array Example int matrix[3][4]; matrix[0][0]: Line: 0 Column: 0 What is the address of this element? Address: 100 0 0 1 2 3 ? ? 1 ? ? 2 ? ? Columns’ index matrix[1][3]: Line: 1 Column: 3 Not accessible 124 Lines’ index ספטמבר 04 matrix[3][4]: Line: 3 Column: 4 Copyright Meir Kalech 21
Two-dimensional Array Example n Usually, a two-dimensional array stores multiple sets of elements. For instance, suppose I have only 10 students (wish I had ) and each student has 5 courses. The goal is to store the courses’ grades of students. We have 3 options: 1. Defining an array of 50 grades. 2. Defining 10 arrays of 5 grades each. 3. Defining a matrix of 10 lines and 5 columns. n Obviously the third option is the best. It is easier for the programmer to access the elements of a matrix. For example, getting an input to the third course of the fourth student is: int grades[10][5]; scanf(“%d”, &grades[3][2]); ספטמבר 04 Copyright Meir Kalech 22
Two-dimensional Array Initialization n Looping through the elements and assigning them a value (or input): int matrix[4][3], i, j; for (i=0; i<4; i++) for (j=0; j<3; j++) matrix[i][j] = i * j; n In definition (using an initialization list): int matrix[4][3] = {1, 2, 3, 4, 5, 6, 7, 8, 9}; OR int matrix[4][3] = ספטמבר 04 {{1, 2, 3}, {4, 5}, {7, 8, 10}, {11}}; Copyright Meir Kalech 23
String n n String is an array of characters. It is treated separately because it is very common to define characters sequentially. When we store a word in an array (string) it is uncomfortable to take care of each character separately. For instance, to go over the characters to be inserted or to print a word. There are library functions which enable simple access to strings. ספטמבר 04 Copyright Meir Kalech 24
String Definition n String definition: n char name[10]; Name consists of 10 chars. But actually we can store only 9 chars, because one char is saved for the null terminator. What is a null? ? ? The null value is 0 or ‘ ’ in the ASCII table. It indicates where is the end of a meaningful string. ספטמבר 04 Copyright Meir Kalech 25
String Initialization char name[13] = “Im a donkey”; I m a d o n k e y ? char name[] = “Im a donkey”; char name[] = {‘I’, ’m’, ’ ‘, ’a’, ’ ‘, ’d’, ’o’, ’n’, ’k’, ’e’, ’y’, ’ ’}; I m a d o n k e y char name[13]; scanf(“%s”, name); //Im a donkey I m ? ? ? ? ? ? gets(name); //Im a donkey I m ספטמבר 04 a d Copyright o n Meir k Kalech e y ? 26
String Initialization char name[13] = “Im a donkey”; Comment: The assignment is permitted only during declaration. There is no assignment operator between strings: char name 1[10], name 2[10]; name 1 = name 2; ספטמבר 04 Copyright Meir Kalech Compilation Error!!! 27
String Library n String manipulations can be done using the <string. h> library (#include <string. h>). This library contains several functions that enable copy, comparison, search, etc… on strings. Comment: strings that are sent to functions as arguments, must be initialized (at least) with null. The following functions are defined for strings: Ø int strlen(char str[]) n n n Returns the length of string str (not including the null terminator). int length; char str 1[10] = “Arie”; length = strlen(str 1); ספטמבר 04 // length = 4 Copyright Meir Kalech 28
String Library n int strcmp(char str 1[], char str 2[]) Compares two strings (lexicographically); Returns: • 0 • >0 • <0 n - the strings are equal. - the first string is greater. - the second string is greater. int compare; char str 1[10] = “Arie”, str 2[] = “arie”; compare = strcmp(str 1, str 2); // compare<0 char *strcpy(char str 1[], char str 2[]) Copies str 2 to str 1 (overwriting). (Used instead of: str 1=str 2; ). Comment: str 1 does not have to be necessarily initialized. char str 1[10] = “Ariela”, str 2[] = “dana”; strcpy(str 1, str 2); // str 1 must be longer than str 2 str 1 ספטמבר 04 A r i e l a ? ? Copyright Meir Kalech ? 29
String Library n int strcmp(char str 1[], char str 2[]) Compares two strings (lexicographically); Returns: • 0 • >0 • <0 n - the strings are equal. - the first string is greater. - the second string is greater. int compare; char str 1[10] = “Arie”, str 2[] = “arie”; compare = strcmp(str 1, str 2); // compare<0 char *strcpy(char str 1[], char str 2[]) Copies str 2 to str 1 (overwriting). (Used instead of: str 1=str 2; ). Comment: str 1 does not have to be necessarily initialized. char str 1[10] = “Ariela”, str 2[] = “dana”; strcpy(str 1, str 2); // str 1 must be longer than str 2 str 1 d ספטמבר 04 a n a ? ? Copyright Meir Kalech ? 30
String Library n char *strcat(char str 1[], char str 2[]) Concatenating str 2 to str 1. Comment: make sure that str 1 is sufficiently long. char str 1[10] = “Arie”, str 2[] = “dana”; strcat(str 1, str 2); str 1 A str 2 r ספטמבר 04 i e ? ? ? Copyright Meir Kalech d a n a 31
String Library n char *strcat(char str 1[], char str 2[]) Concatenating str 2 to str 1. Comment: make sure that str 1 is sufficiently long. char str 1[10] = “Arie”, str 2[] = “dana”; strcat(str 1, str 2); str 1 A str 2 r i e d a n a ? d a n a char str 1[10] = “Arie”, str 2[] = “daniela”; strcat(str 1, str 2); str 1 A str 2 r ספטמבר 04 i e ? ? ? d Copyright Meir Kalech a n i e l a 32
String Library n char *strcat(char str 1[], char str 2[]) Concatenating str 2 to str 1. Comment: make sure that str 1 is sufficiently long. char str 1[10] = “Arie”, str 2[] = “dana”; strcat(str 1, str 2); str 1 A str 2 r i e d a n a ? d a n a char str 1[10] = “Arie”, str 2[] = “daniela”; strcat(str 1, str 2); str 1 A str 2 r i e d a n i e l a DANGEROUS!!! ספטמבר 04 Copyright Meir Kalech 33
Array as Parameter to Function What does an array name indicate ? ? ? An ADDRESS!!! n n When an array is passed as an argument to a function, only its address is sent. There are 2 ways to indicate types of (array) addresses: n n type[] (examples: char[], int[], etc…) type * (examples: char *, int *, etc…) ספטמבר 04 Copyright Meir Kalech 34
Array as Parameter to Function - Definition sizeof(arr) is the number of bytes in arr (12) BU T… sizeof(vector) is only 4 since only the address of arr is sent, and address is 4 bytes ספטמבר 04 void print_reverse(char *string); int sum_array(int vector[], int size); void main() { int sum, size, arr[]={1, 2, 3}; char str[]=“sharon”; size = sizeof(arr)/sizeof(int); sum = sum_array(arr, size); print_reverse(str); } void print_reverse(char *string) { int i, size = strlen(string); for(i=size-1; i>=0; i--) printf(“%c”, string[i]); } int sum_array(int vector[], int size) { int sum = 0, i; for(i=0; i<size; i++) sum += vector[i]; return sum; } Copyright Meir Kalech 35
Array as Parameter - Stack n n n An array address enables access to its elements using the operator []. With operator [] we can even change the values of the array, although the array is defined in main. Comment: It’s not possible to change primitive types (char, int…) variables that are passed as arguments to a function. ספטמבר 04 Copyright Meir Kalech 36
Array as Parameter – Stack: Example initialize gets arr, size and arr[0]. It assigns arr[0] to the first size elements of arr i void main() { int arr[4]={1, 2, 3, 4}, size=3; initialize(arr, size, arr[0]); } first initialize int initialize(int vector[], int len, int first) { int i; for(i=1; i<len; i++) vector[i] = first; len = first = 8; return len; } main ספטמבר 04 Copyright Meir Kalech len vector Return address Returned value size=3 arr 100 1 2 3 4 37
Array as Parameter – Stack: Example After passing of arguments void main() { int arr[4]={1, 2, 3, 4}, size=3; initialize(arr, size, arr[0]); } i first=1 initialize int initialize(int vector[], int len, int first) { int i; for(i=1; i<len; i++) vector[i] = first; len = first = 8; return len; } main ספטמבר 04 Copyright Meir Kalech len=3 vector=100 1024 Returned value size=3 arr 100 1 2 3 4 38
Array as Parameter – Stack: Example After initial execution i=3 void main() { int arr[4]={1, 2, 3, 4}, size=3; initialize(arr, size, arr[0]); } first=8 initialize int initialize(int vector[], int len, int first) { int i; for(i=1; i<len; i++) vector[i] = first; len = first = 8; return len; } vector[i]: 100+i*sizeof(int) [] ספטמבר 04 main Copyright Meir Kalech len=8 vector=100 1024 Returned value size=3 arr 100 1 1 1 4 39
Array as Parameter – Stack: Example After returned value updating void main() { int arr[4]={1, 2, 3, 4}, size=3; initialize(arr, size, arr[0]); } i=3 first=8 initialize int initialize(int vector[], int len, int first) { int i; for(i=1; i<len; i++) vector[i] = first; len = first = 8; return len; } main ספטמבר 04 Copyright Meir Kalech len=8 vector=100 1024 8 size=3 arr 100 1 1 1 4 40
Array as Parameter – Stack: Example After return of value Conclusion: size wasn’t changed arr was changed void main() { int arr[4]={1, 2, 3, 4}, size=3; initialize(arr, 8 size, arr[0]); } int initialize(int vector[], int len, int first) { int i; for(i=1; i<len; i++) vector[i] = first; len = first = 8; return len; } main ספטמבר 04 Copyright Meir Kalech 8 size=3 arr 100 1 1 1 4 41
Call by Value Passing arguments by value: the arguments are copied to the local parameters of the function. n Conclusion: if we want to pass an argument so as to change its value in the function, we can not pass it by value. n ספטמבר 04 Copyright Meir Kalech 42
Call by Address Passing an array as argument: its address is passed by value (a local parameter stores the address). But, the array’s elements are accessible by using the operator []. n Conclusion: if we want to pass an argument in order to change it in the function, we should pass it by address. n ספטמבר 04 Copyright Meir Kalech 43
2 D-array as Parameter n n n 2 D array name is also an address. Its type is: type[][]. When defining a function that gets a 2 D array, it’s necessary to add the size of the second [] (columns). Explanation: let’s describe what happens with access to an element by [][]: int matrix[2][4]; matrix[1][2] = 4; matrix is a vector of two 1 D vectors. matrix[1]: matrix+1*sizeof(matrix[0]) – assume matrix is at address 100; then matrix[1] is at address 100+16. (matrix[1])[2]: 116+2*sizeof(int). The operator [] accesses the value of the address 124 (4 is assigned to this value). ספטמבר 04 Copyright Meir Kalech 44
2 D-array as Parameter n n When passing an array to a function, only its address is passed. When accessing an array in the function with the following command: matrix[1][2] = 4; The compiler doesn’t know to decode the term matrix[1], because its address is known but sizeof(matrix[0]) depends on 1 D vector length. void func(int mat[][]); void main() { int matrix[2][4]; func(matrix); } void func(int mat[][]) { mat[1][2] = 4; } ספטמבר 04 matrix address 100 ? ? mat 100 Copyright Meir Kalech The compiler shouts that it doesn’t know the size of each vector in mat!!! 45
2 D-array as Parameter n So note the correct declaration now. void func(int mat[][4]); void main() { int matrix[2][4]; func(matrix); } void func(int mat[][4]) { mat[1][2]=4; } ספטמבר 04 matrix address 100 mat 100 ? ? Now the compiler knows that sizeof(mat[0]) is 4*4=16 Copyright Meir Kalech 46