Title: Dale Roberts, Lecturer
1Department of Computer and Information
Science,School of Science, IUPUI
CSCI 230
Arrays Strings and Parameter Passing
- Dale Roberts, Lecturer
- IUPUI
- droberts_at_cs.iupui.edu
2Character Arrays
- Character arrays
- String is really a static array of characters,
ex first - Character arrays can be initialized using string
literals - char string1 "first"
- Null character '\0' terminates strings
- string1 actually has 6 elements
- It is equivalent to char string1 'f', 'i',
'r', 's', 't', '\0' - Can access individual characters
- string1 3 is character s
- Array name is address of array, so not needed
for scanf char char string220 -
- scanf( "s", string2 )
- Can read a string with max of size 19 and a null
character. - Reads characters until whitespace (space, tab,
carriage-return, newline, vertical tab)
encountered - Can write beyond end of array, be careful
Null character (indicates string termination)
is NOT used, why?
3Passing Arrays to Functions
- Passing arrays
- To pass an array argument to a function, specify
the name of the array without any brackets - int myArray 24
- ...
- myFunction( myArray, 24 )
- ...
- Array size usually passed to function
- Arrays passed call-by-reference
- the called functions can modify the element
values in the callers original array - Name of array is the address of first element of
the array - Function knows where the array is stored.
Therefore, when the called function modifies
array elements in its function body, it is
modifying the actual elements of array in the
original memory locations
main()
myArray
myFunction()
4Passing Arrays to Functions (cont.)
- Example include ltstdio.hgt
- main()
-
- int a10
- printf(a p \n a0 p\n, a, a0)
-
- output a FFEE
- a0 FFEE
- Passing array elements
- Individual elements of an array are passed by
call-by-value - Pass subscripted name (i.e., myArray 3 ) to
function - Example compare(a0, a1)
- An array is a vector while individual elements
are scalars. - Function prototype
- void modifyArray( int b, int arraySize )
- Parameter names optional in prototype
- int b could be written int
will be passed by value
5- Function definitions
- Pass array to a function
- Pass array element to a function
- Print
Entire arrays passed call-by-reference, and can
be modified
Array elements passed call-by-value, and cannot
be modified
6Effects of passing entire array call by
reference The values of the original array
are 0 1 2 3 4 The values of the modified
array are 0 2 4 6 8 Effects of passing
array element call by value The value of
a3 is 6 Value in modifyElement is 12 The value
of a3 is 6
Program Output