Date post: | 04-Apr-2018 |
Category: |
Documents |
Upload: | anurag-damera |
View: | 225 times |
Download: | 0 times |
of 51
7/30/2019 3.Arrays and Pointers
1/51
Chapter 6 - Arrays
1
Outline6.1 Introduction6.2 Arrays6.3 Declaring Arrays6.4 Examples Using Arrays6.5 Passing Arrays to Functions
6.6 Sorting Arrays6.7 Case Study: Computing Mean, Median and Mode Using Arrays6.8 Searching Arrays6.9 Multiple-Subscripted Arrays
7/30/2019 3.Arrays and Pointers
2/51
6.1 Introduction
Arrays
Structures of related data items
Static entity
same size throughout program Dynamic data structures discussed in Chapter 12
2
7/30/2019 3.Arrays and Pointers
3/51
6.2 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 ]
3
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]
-45
6
0
72
1543
-89
0
62
-3
1
6453
78
c[0]
c[1]
c[2]
c[3]
c[11]
c[10]
c[9]
c[8]
c[7]
c[5]
c[4]
7/30/2019 3.Arrays and Pointers
4/51
6.2 Arrays
Array elements are like normal variablesc[ 0 ] = 3;
printf( "%d", c[ 0 ] );
Perform operations in subscript. If x equals 3
c[ 5 - 2 ] == c[ 3 ] == c[ x ]
4
7/30/2019 3.Arrays and Pointers
5/51
Array Elements & IndicesEach member of an array is identified by unique index or
subscript assigned to it
The dimension of an array is determined by the number of
indices needed to uniquely identify each element.
An index is a positive integer enclosed in [ ]placed
immediately after the array name.
An index holds integer values starting with zero.
An array with 11 elements will look like -
7/30/2019 3.Arrays and Pointers
6/51
Defining an Array
An array has some particular characteristics and has to be
defined with them.
These characteristics include -
which indicates the location of the
first member of the array.
a constant evaluating to a +ve value
7/30/2019 3.Arrays and Pointers
7/51
Defining an Array - I
An array is defined in the same way as a variable is defined
except that the array name is followed by one or more
expressions, enclosed within square brackets [ ], specifying
the array dimension.
7/30/2019 3.Arrays and Pointers
8/51
Norms with Arrays
All elements of an array are of the same type.
Each element of an array can be used anywhere that a
variable is allowed or required.
Each element of an array can be referenced using a variable
or an integer expression.
Arrays can have their data types like int, char, float
7/30/2019 3.Arrays and Pointers
9/51
Array Handling In C
7/30/2019 3.Arrays and Pointers
10/51
Array Handling In CAn array is treated differently from a variable in C.
Two arrays, even if they are of the same type and size cannot
be tested for equality.
It is not possible to assign one array directly to another.
Values cannot be assigned to an array on the whole, instead
values are assigned to the elements of the array.
7/30/2019 3.Arrays and Pointers
11/51
Array Initialization
In the following example the array elements have been
assigned valued using the for loop.
In case of extern and static arrays, the elements are
automatically initialized to zero.
Each element of an Automatic array needs to be initialized
separately.
7/30/2019 3.Arrays and Pointers
12/51
Reading Unknown Number Of ElementsConsider the following case -
A program is written to calculate the average of given numbers
and print it. The total numbers to be input can range from 1 to
50. An array would naturally be considered the best way to
store the numbers. But a problem may arise in when fewer
numbers than the maximum length of the array is entered.
Solution -
7/30/2019 3.Arrays and Pointers
13/51
7/30/2019 3.Arrays and Pointers
14/51
Strings / Character ArraysOutput -
The input for the above is of 4 characters and the 5 th
character is the null character.
The above output is for an input of 5 characters.
7/30/2019 3.Arrays and Pointers
15/51
String FunctionsC supports a wide range of string functions, which are
found in the standard header file
Some of them are listed below -
7/30/2019 3.Arrays and Pointers
16/51
Two Dimensional ArraysThe simplest and the most commonly used
multi - dimensional array is the two - dimensional array.
A two-dimensional array can be thought of as an array
of two single dimensional arrays.
A two - dimensional array looks like a school time-table
consisting of rows and columns.
A twodimensional array is declared as -
7/30/2019 3.Arrays and Pointers
17/51
Initialization of Multidimensional Arrays
The result of the above assignment will be as follows :
7/30/2019 3.Arrays and Pointers
18/51
Initialization of Multidimensional Arrays - I
7/30/2019 3.Arrays and Pointers
19/51
Initialization of Multidimensional Arrays - II
The result of the assignment will be as follows :
A two - dimensional string array is declared in the
following manner :
7/30/2019 3.Arrays and Pointers
20/51
6.3 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 ];
20
7/30/2019 3.Arrays and Pointers
21/51
6.4 Examples Using Arrays
Initializersint 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
21
7/30/2019 3.Arrays and Pointers
22/51
6.4 Examples Using Arrays
Character arrays String first is really a static array of characters Character arrays can be initialized using string literals
char string1[] = "first";
Null character '\0' terminates strings string1 actually has 6 elements
It is equivalent tocharstring1[]={'f','i','r','s','t','\0'}; Can access individual charactersstring1[3] is character s
Array name is address of array, so & not needed forscanfscanf("%s",string2);
Reads characters until whitespace encountered Can write beyond end of array, be careful
22
1 /* Fig. 6.10: fig06 10.c
7/30/2019 3.Arrays and Pointers
23/51
2000 Prentice Hall, Inc.
All rights reserved.
1. Initialize strings
2. Print strings
2.1 Define loop
2.2 Print characters
individually
2.3 Input string
3. Print string
Program Output 23
1 / Fig. 6.10: fig06_10.c
2 Treating character arrays as strings */
3 #include
4
5 int main()
6 {
7 char string1[ 20 ], string2[] = "string literal";
8 int i;
9
10 printf(" Enter a string: ");
11 scanf( "%s", string1 );
12 printf( "string1 is: %s\nstring2: is %s\n"
13 "string1 with spaces between characters is:\n",
14 string1, string2 );
15
16 for ( i = 0; string1[ i ] != '\0'; i++ )
17 printf( "%c ", string1[ i ] );
18
19 printf( "\n" );
20 return 0;
21 }
Enter a string: Hello therestring1 is: Hellostring2 is: string literalstring1 with spaces between characters is:
H e l l o
7/30/2019 3.Arrays and Pointers
24/51
6.5 Passing Arrays to Functions
Passing arrays To pass an array argument to a function, specify the name
of the array without any bracketsint myArray[24];myFunction(myArray,24);
Array size usually passed to function
Arrays passed call-by-reference
Name of array is address of first element
Function knows where the array is stored
Modifies original memory locations Passing array elements
Passed by call-by-value
Pass subscripted name (i.e.,myArray[3]) to function24
7/30/2019 3.Arrays and Pointers
25/51
6.5 Passing Arrays to Functions
Function prototypevoid modifyArray( int b[], intarraySize );
Parameter names optional in prototype
int b[] could be written int []
int arraySize could be simply int
25
1 /* Fig. 6.13: fig06 13.c
7/30/2019 3.Arrays and Pointers
26/51
2000 Prentice Hall, Inc.
All rights reserved.
1. Function definitions
2. Pass array to afunction
2.1 Pass array elementto a function
3. Print
26
g g _
2 Passing arrays and individual array elements to functions */
3 #include
4 #define SIZE 5
5
6 voidmodifyArray( int [], int ); /* appears strange */
7 voidmodifyElement( int );
89 int main()
10 {
11 int a[ SIZE ] = { 0, 1, 2, 3, 4 }, i;
12
13 printf( "Effects of passing entire array call "
14 "by reference:\n\nThe values of the "
15 "original array are:\n" );
16
17 for ( i = 0; i
7/30/2019 3.Arrays and Pointers
27/51
2000 Prentice Hall, Inc.
All rights reserved.
3.1 Functiondefinitions
Program Output
27
34 voidmodifyArray( int b[], int size )
35 {
36 int j;
37
38 for ( j = 0; j
7/30/2019 3.Arrays and Pointers
28/51
6.6 Sorting Arrays
Sorting data Important computing application Virtually every organization must sort some data
Bubble sort (sinking sort) Several passes through the array Successive pairs of elements are compared
If increasing order (or identical ), no change If decreasing order, elements exchanged
Repeat
Example: original: 3 4 2 6 7 pass 1: 3 2 4 6 7 pass 2: 2 3 4 6 7 Small elements "bubble" to the top
28
7/30/2019 3.Arrays and Pointers
29/51
6.8 Searching Arrays: Linear
Search and Binary Search
Search an array for a key value
Linear search
Simple Compare each element of array with key value
Useful for small and unsorted arrays
29
7/30/2019 3.Arrays and Pointers
30/51
6.8 Searching Arrays: Linear
Search and Binary Search
Binary search For sorted arrays
Comparesmiddle element with key If equal, match found Ifkey < middle, looks in first half of array
Ifkey > middle, looks in last half
Repeat
Very fast; at most n steps, where 2n > number ofelements
30 element array takes at most 5 steps
25 > 30 so at most 5 steps
30
5
7/30/2019 3.Arrays and Pointers
31/51
6.9 Multiple-Subscripted Arrays
Multiple subscripted arrays
Tables with rows and columns (mby n array)
Like matrices: specify row, then column
31
Row 0
Row 1
Row 2
Column 0 Column 1 Column 2 Column 3
a[0][0]a[1][0]
a[2][0]
a[0][1]a[1][1]
a[2][1]
a[0][2]a[1][2]
a[2][2]
a[0][3]a[1][3]
a[2][3]
Row subscriptArray name
Column subscript
7/30/2019 3.Arrays and Pointers
32/51
6.9 Multiple-Subscripted Arrays
Initialization
int b[2][2]={{1,2},{3,4}}; Initializers grouped by row in braces
If not enough, unspecified elements set to zero
int b[2][2]={{1},{3,4}}; Referencing elements
Specify row, then column
printf("%d",b[0][1]);
32
1 2
3 4
1 0
3 4
7/30/2019 3.Arrays and Pointers
33/51
Session 7
7/30/2019 3.Arrays and Pointers
34/51
What is a Pointer?A pointer is a variable, which contains the address of a memory
location of another variable.
If one variable contains the address of another variable, the first
variable is said to point to the second variable.
A pointer provides an indirect method of accessing the value of
a data item.
Pointers can point to variables of other fundamental data types
like int, char, or double or data aggregates like arrays or
structures.
7/30/2019 3.Arrays and Pointers
35/51
What are Pointers used for?Pointers are used in situations when passing actual values is
difficult or not desired. Some of the situations where pointers can be
used are -
To return more than one value from a function.
To pass arrays and strings more conveniently from onefunction to another.
To manipulate arrays easily by moving pointers to them
instead of moving the arrays itself.
To allocate memory and access it (Direct Memory
Allocation).
To create complex data structures, such as linked lists.
7/30/2019 3.Arrays and Pointers
36/51
Pointer VariablesIf a variable is to be used as a pointer, it must be declared.
A pointer declaration consists of a base type, a *, and a variable
name.
General declaration syntax is : -
For Example:
7/30/2019 3.Arrays and Pointers
37/51
Pointer OperatorsThere are 2 special operators which are used with pointers :
The & operator is a unary operator and it returns the memory address
of the operand.
The second operator * is the complement of &. It is a unary operator
and returns the value contained in the memory location pointed to by
the pointer variables value.
7/30/2019 3.Arrays and Pointers
38/51
Assigning Values To PointersValues can be assigned to pointers through the & operator.
The assignment statement will be -
Here the address of var is stored in the variable ptr_var.
It is also possible to assign values to pointers through another pointer
variable pointing to a data item of the same data type.
7/30/2019 3.Arrays and Pointers
39/51
Assigning Values To Pointers - IVariables can be assigned values through their pointers as well.
The above declaration will assign 10 to the variable var if ptr_var
points to var.
7/30/2019 3.Arrays and Pointers
40/51
Pointer ArithmeticAddition and subtraction are the only operations that can be
performed on pointers.
Take a look at the following example :
Let var be an integer type variable
having the value 500 and stored at the
address 1000.
Then ptr_var has the value 1000 stored in it. Since integers are 2
bytes long, after the expression ptr_var++; ptr_var will have the
value as 1002 and not 1001.
7/30/2019 3.Arrays and Pointers
41/51
Some More Examples
Each time a pointer is incremented, it points to the memory location
of the next element of its base type.
Each time it is decremented it points to the location of the previous
element.
All other pointers will increase or decrease depending on the length
of the data type they are pointing to.
7/30/2019 3.Arrays and Pointers
42/51
Pointer ComparisonsTwo pointers can be compared in a relational expression provided
both the pointers are pointing to variables of the same type.
Consider that ptr_a and ptr_b are 2 pointer variables, which point to
data elements a and b. In this case the following comparisons are
possible:
7/30/2019 3.Arrays and Pointers
43/51
Pointers as Function Arguments
The address of the data item is passed and thus the function can
freely access the contents of that address from within the function
When pointers are passed to a function:
The program routine can access the variables that lie within the
scope of the function.
7/30/2019 3.Arrays and Pointers
44/51
The function as well as the calling routine recognizes any change
made to the contents of the address.
In this way, function arguments permit data-items to be altered in the
calling routine and the function.
When the arguments are pointers or arrays, a call by reference is made
to the function as opposed to a call by value for the variable arguments.
Pointers as Function Arguments - I
7/30/2019 3.Arrays and Pointers
45/51
Function Definition
indicates that the arguments ptr_str points to type char and ptr_int
points to type int.
The function can be invoked by the statement,
where pstr is declared as a pointer and the address of the variable var
is passed.
7/30/2019 3.Arrays and Pointers
46/51
Assigning a value through,
Function Definition - I
in the function can now assign values to the variable var in the calling
routine, enabling a two way transfer to and from the function.
7/30/2019 3.Arrays and Pointers
47/51
Pointers and Single Dimensional Arrays
The address of an array element can be expressed in two ways :
By writing the actual array element preceded by the ampersand
sign.
By writing an expression in which the subscript is added to the
array name.
The following program shows the relationship between array
elements and their addresses.
7/30/2019 3.Arrays and Pointers
48/51
Pointers and Single Dimensional Arrays
7/30/2019 3.Arrays and Pointers
49/51
Pointers and Multi Dimensional Arrays
A two-dimensional array can be defined as a pointer to a group of
contiguous one-dimensional arrays.
A two-dimensional array declaration can be written as :
instead of
7/30/2019 3.Arrays and Pointers
50/51
Pointers & StringsUsing strings as pointers can be explained with the help of the
7/30/2019 3.Arrays and Pointers
51/51
Allocating MemoryThe following example uses a two-dimensional array to record
marks of 5 students for 10 subjects.
It uses pointers and malloc() function, to assign memory.