Download presentation
Presentation is loading. Please wait.
2
ספטמבר 04Copyright Meir Kalech1 C programming Language Chapter 4: Arrays and Strings
3
ספטמבר 04Copyright Meir Kalech2 Assume a C program stores the ages of 3 children. Which variables should we define? Very good! 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. Array Structure
4
ספטמבר 04Copyright Meir Kalech3 int ages[10]; Name of the array = First address of the array Array Definition Elements typeArray nameNumber of elements 136132128124120116112108104100 ?????????? 9876543210 address value index
5
ספטמבר 04Copyright Meir Kalech4 sizeof() operator gets a type or variable and returns its size in bytes. For example: int x; printf(“%d”, sizeof(int)); // print 4 printf(“%d”, sizeof(x));// print 4 Array subscripting operator [] denotes an index in an array and enables access to the value of the addressed array index. For example: int ages[10];// definition ages[3] = 23;// access printf(“%d”, ages[3]);// access What is sizeof(ages)? Array Definition 4 * 10 = 40
6
ספטמבר 04Copyright Meir Kalech5 Array Subscripting Operator [] 136132128124120116112108104100 ??????23??? 9876543210 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.
7
ספטמבר 04Copyright Meir Kalech6 DANGEROUS!!! Be careful!!! This address is not allocated to your program Array Subscripting Operator [] 140136132128124120116112108104100 ???????23??? 109876543210 What happens when accessing the 10’th place of ages: ages[10] = 30 ??? ages[10]
8
ספטמבר 04Copyright Meir Kalech7 No boundary checks are performed by the computer. 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! C does not have any operator to work with an array “ as a whole ” : For instance: we can ’ t assign into an array multiple values at once; we can ’ t print all the array at once, etc … question: what is the output of - printf( “ %p ”, ages); Notes on Arrays 100 printf( “ %p ”, ages);
9
ספטמבר 04Copyright Meir Kalech8 Array Initialization Within declaration (using an initialization list): int array[5] = {5,8,2,7}; If the size of array is not specified, size is determined by the number of initializing values provided: int array[] = {5,8,2,7}; 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]); 07285 43210 7285 3210 Automatically initialized to 0
10
ספטמבר 04Copyright Meir Kalech9 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; } 04321 43210 Array initialization
11
ספטמבר 04Copyright Meir Kalech10 Example First iteration: 04321 43210 temp i=0j=4
12
ספטמבר 04Copyright Meir Kalech11 Example First iteration: 04321 43210 1 temp i=0j=4 temp = array[i];
13
ספטמבר 04Copyright Meir Kalech12 Example First iteration: 04320 43210 1 temp i=0j=4 array[i] = array[j];
14
ספטמבר 04Copyright Meir Kalech13 Example First iteration: 14320 43210 1 temp i=0j=4 array[j] = temp;
15
ספטמבר 04Copyright Meir Kalech14 Example First iteration: 14320 43210 1 temp i=1 j=3 i++, j--
16
ספטמבר 04Copyright Meir Kalech15 Example Second iteration: 14320 43210 2 temp i=1j=3 temp = array[i];
17
ספטמבר 04Copyright Meir Kalech16 Example Second iteration: 14340 43210 2 temp i=1 j=3 array[i] = array[j];
18
ספטמבר 04Copyright Meir Kalech17 Example Second iteration: 2 temp i=1 j=3 array[j ] = temp; 12340 43210
19
ספטמבר 04Copyright Meir Kalech18 Example Second iteration: 12340 43210 2 temp i=2 j=2 i++, j-- i is not smaller than j so STOP!!!
20
ספטמבר 04Copyright Meir Kalech19 Two-dimensional Array Two-dimensional (2D) array is an array of arrays. For instance: the definition int matrix[3][4] means 3 arrays of 4 integers each. As for a one-dimensional (1D) array, the elements will be created sequentially in memory (in row-major order). So what is the difference between the two??? ???? ? 43210 ????? 98765 ?? 1110 116112108104100136132128124120144140
21
ספטמבר 04Copyright Meir Kalech20 Two-dimensional Array 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: The first [] locates the requested array (the line). The second [] locates the requested element in the line array (the column). Conclusion: 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.
22
ספטמבר 04Copyright Meir Kalech21 Two-dimensional Array Example int matrix[3][4]; 3210 ???? 0 ???? 1 ???? 2 Columns ’ index Lines ’ index matrix[1][3]: Line: 1 Column: 3 matrix[0][0]: Line: 0 Column: 0 matrix[3][4]: Line:3 Column: 4 What is the address of this element? Address:100 124 Not accessible
23
ספטמבר 04Copyright Meir Kalech22 Two-dimensional Array Example 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. 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]);
24
ספטמבר 04Copyright Meir Kalech23 Two-dimensional Array Initialization 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; In definition (using an initialization list): int matrix[4][3] = {1, 2, 3, 4, 5, 6, 7, 8, 9}; OR int matrix[4][3] ={{1, 2, 3}, {4, 5}, {7, 8, 10}, {11}};
25
ספטמבר 04Copyright Meir Kalech24 String 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.
26
ספטמבר 04Copyright Meir Kalech25 String Definition String definition: 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 ‘\0’ in the ASCII table. It indicates where is the end of a meaningful string.
27
ספטמבר 04Copyright Meir Kalech26 String Initialization char name[13] = “ Im a donkey ” ; ?\0yeknodamI char name[] = “ Im a donkey ” ; char name[] = { ‘ I ’, ’ m ’, ’ ‘, ’ a ’, ’ ‘, ’ d ’, ’ o ’, ’ n ’, ’ k ’, ’ e ’, ’ y ’, ’ \0 ’ }; \0yeknodamI ?????????? mI ? yeknod a mI char name[13]; scanf( “ %s ”, name);//Im a donkey gets(name);//Im a donkey
28
ספטמבר 04Copyright Meir Kalech27 String Initialization char name[13] = “ Im a donkey ” ; Comment: The assignment is permitted only during declaration. There is no assignment operator between strings: char name1[10], name2[10]; name1 = name2; Compilation Error!!!
29
ספטמבר 04Copyright Meir Kalech28 String Library String manipulations can be done using the library ( #include ). 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[]) Returns the length of string str (not including the null terminator). int length; char str1[10] = “Arie”; length = strlen(str1);// length = 4
30
ספטמבר 04Copyright Meir Kalech29 String Library int strcmp(char str1[], char str2[]) Compares two strings (lexicographically); Returns: 0- the strings are equal. >0- the first string is greater. <0- the second string is greater. int compare; char str1[10] = “Arie”, str2[] = “arie”; compare = strcmp(str1, str2);// compare<0 char *strcpy(char str1[], char str2[]) Copies str2 to str1 (overwriting). (Used instead of: str1=str2;). Comment: str1 does not have to be necessarily initialized. char str1[10] = “Ariela”, str2[] = “dana”; strcpy(str1, str2);// str1 must be longer than str2 ???\0aleirA str1
31
ספטמבר 04Copyright Meir Kalech30 String Library int strcmp(char str1[], char str2[]) Compares two strings (lexicographically); Returns: 0- the strings are equal. >0- the first string is greater. <0- the second string is greater. int compare; char str1[10] = “Arie”, str2[] = “arie”; compare = strcmp(str1, str2);// compare<0 char *strcpy(char str1[], char str2[]) Copies str2 to str1 (overwriting). (Used instead of: str1=str2;). Comment: str1 does not have to be necessarily initialized. char str1[10] = “Ariela”, str2[] = “dana”; strcpy(str1, str2);// str1 must be longer than str2 ???\0a anad str1
32
ספטמבר 04Copyright Meir Kalech31 String Library char *strcat(char str1[], char str2[]) Concatenating str2 to str1. Comment: make sure that str1 is sufficiently long. char str1[10] = “Arie”, str2[] = “dana”; strcat(str1, str2); ?????\0eirA anad str1str2
33
ספטמבר 04Copyright Meir Kalech32 String Library char *strcat(char str1[], char str2[]) Concatenating str2 to str1. Comment: make sure that str1 is sufficiently long. char str1[10] = “Arie”, str2[] = “dana”; strcat(str1, str2); ?\0anadeirA anad str1str2 char str1[10] = “Arie”, str2[] = “daniela”; strcat(str1, str2); ?????\0eirAla einad str1str2
34
ספטמבר 04Copyright Meir Kalech33 String Library char *strcat(char str1[], char str2[]) Concatenating str2 to str1. Comment: make sure that str1 is sufficiently long. char str1[10] = “Arie”, str2[] = “dana”; strcat(str1, str2); ?\0anadeirA anad str1str2 char str1[10] = “Arie”, str2[] = “daniela”; strcat(str1, str2); leinadeirAla\0einad str1str2 DANGEROUS!!!
35
ספטמבר 04Copyright Meir Kalech34 Array as Parameter to Function 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: type[](examples: char[], int[], etc…) type *(examples: char *, int *, etc…) What does an array name indicate ??? An ADDRESS!!!
36
ספטמבר 04Copyright Meir Kalech35 Array as Parameter to Function - Definition 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; } sizeof(arr) is the number of bytes in arr (12) sizeof(vector) is only 4 since only the address of arr is sent, and address is 4 bytes BU T …
37
ספטמבר 04Copyright Meir Kalech36 Array as Parameter - Stack 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.
38
ספטמבר 04Copyright Meir Kalech37 Array as Parameter – Stack: Example i first len vector Return address Returned value size=3 void main() { int arr[4]={1,2,3,4}, size=3; initialize(arr, 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; } initialize main 4321 arr 100 initialize gets arr, size and arr[0]. It assigns arr[0] to the first size elements of arr
39
ספטמבר 04Copyright Meir Kalech38 Array as Parameter – Stack: Example i first=1 len=3 vector=100 1024 Returned value size=3 void main() { int arr[4]={1,2,3,4}, size=3; initialize(arr, 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; } initialize main 4321 arr 100 After passing of arguments
40
ספטמבר 04Copyright Meir Kalech39 Array as Parameter – Stack: Example i=3 first=8 len=8 vector=100 1024 Returned value size=3 void main() { int arr[4]={1,2,3,4}, size=3; initialize(arr, 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; } initialize main 4111 arr 100 After initial execution vector[i]: 100+i*sizeof(int) []
41
ספטמבר 04Copyright Meir Kalech40 Array as Parameter – Stack: Example i=3 first=8 len=8 vector=100 1024 8 size=3 void main() { int arr[4]={1,2,3,4}, size=3; initialize(arr, 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; } initialize main 4111 arr 100 After returned value updating
42
ספטמבר 04Copyright Meir Kalech41 Array as Parameter – Stack: Example 8 size=3 void main() { int arr[4]={1,2,3,4}, size=3; initialize(arr, 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 4111 arr 100 After return of value 8 Conclusion : size wasn ’ t changed arr was changed
43
ספטמבר 04Copyright Meir Kalech42 Call by Value Passing arguments by value: the arguments are copied to the local parameters of the function. Conclusion: if we want to pass an argument so as to change its value in the function, we can not pass it by value.
44
ספטמבר 04Copyright Meir Kalech43 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 []. Conclusion: if we want to pass an argument in order to change it in the function, we should pass it by address.
45
ספטמבר 04Copyright Meir Kalech44 2D-array as Parameter 2D array name is also an address. Its type is: type[][]. When defining a function that gets a 2D 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 1D 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).
46
ספטמבר 04Copyright Meir Kalech45 2D-array as Parameter 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 1D vector length. void func(int mat[][]); void main() { int matrix[2][4]; func(matrix); } void func(int mat[][]) { mat[1][2] = 4; } ???? ???? matrix address 100 100 mat The compiler shouts that it doesn’t know the size of each vector in mat!!!
47
ספטמבר 04Copyright Meir Kalech46 2D-array as Parameter 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; } ???? ???? matrix address 100 100 mat Now the compiler knows that sizeof(mat[0]) is 4*4=16
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.