450 likes | 1.67k Views
ARRAYS IN C. BY MARK A. WHAT IS AN ARRAY. Array is a finite set of variables of the same basic type Define an array by …. Int arr [ i ]; i is the number of elements in an array Array always starts with zero, last element in array is i-1;. Multidimensional Arrays.
E N D
ARRAYS IN C BY MARK A
WHAT IS AN ARRAY • Array is a finite set of variables of the same basic type • Define an array by …. Intarr[i]; • i is the number of elements in an array • Array always starts with zero, last element in array is i-1;
Multidimensional Arrays • Array stated as intarr[1] is an array of one dimension with 1 element • Multidimensional arrays are stated as • Intarr[i][j] where i is rows and j is cols or… • Arr[rows][cols] • Multidimensional arrays can be used for things like matrix classes
Init Arrays • Can define arrays many ways • Intarry[]; //size later determined • Int array[5]; // predetermined size 0-4 • Int array[4] = {1,2,3,4}; • Int array[2][3] = {{1,2,3}, {4,5,6}}; • Can access array elements such as an arr[5].. • Arr[0] = 1; arr[2] = 5; 2[arr]; • Or for an array of arr[2][2] • Arr[1][0] = 5;
can use other variables • Can use characters in array… for example • Char arr[] = “hello”; • Can assign arrays to variables such as • Int x = arr; • Printf(“%s”, x); // prints whole array of chars • When printing integer arrays, must print individual printf statements for each array element - (use loops) • Another idea is to use a pointer • Printf(“%d”, *array); // returns 1st element in array • Printf(“%d”, *(array+1));// returns 2nd element in array
Memory Allocation • Arrays are all about memory allocation. In the following, the int age[] starts at 924 through 931. Thus when you use the pointer *(age+1) you will be accessing second element at 926.
For loops • for(i=0; I<size; i++) { printf(“array [%d]\n", arr[i]); }
Array problems • Can’t copy same size arrays over • Must physically enter each one as well • Array1[0] = array2[0]; • Array1[1] = array2[1]; • You will see this a lot in matrix codes • Run time errors happen a lot, because programs don’t check for bounds on arrays, (if you try to access an element out of bounds)
Assignment • Research how to use strcmp, strcat, strlen, strcpy,