Array in C-1
Array in C-1
• Arrays
– Structures of related data items
• A few types
– C-like, pointer-based arrays
c[0] -45
c[1] 6
c[2] 0
c[3] 72
c[4] 1543
c[5] -89
c[6] 0
c[7] 62
c[8] -3
c[9] 1
c[10] 6453
c[11] 78
• Initializers
int n[ 5 ] = { 1, 2, 3, 4, 5 };
– If not enough initializers, rightmost elements become 0
– If too many initializers, a syntax error is generated
int n[ 5 ] = { 0 }
#include <stdio.h>
int main()
{
int kp[] = {25, 50, 75, 100};
int i;
for (i = 0; i < 4; i++)
{
printf("%d\n", kp[i]);
}
return 0;
}
Loop Through an Array
#include <stdio.h>
Set Array Size void main()
{
int kp[4];
kp[0] = 25;
kp[1] = 50;
kp[2] = 75;
kp[3] = 100;
printf("%d\n", kp[0]);
}
Loop Through an Array
#include <stdio.h>
Set Array Size void main()
{
int kp[] = {25, 50, 75, 3.15, 5.99};
int i;
for (i = 0; i < 5; i++)
{
printf("%d\n", kp[i]);
}
}
Loop Through an Array
#include <stdio.h>
Get Array Size int main()
{
int kp[] = {10, 25, 50, 75, 100};
printf("%lu", sizeof(kp));
return 0;
}
Examples Using Arrays
• Strings
– Arrays of characters
– All strings end with null ('\0')
– Examples:
char string1[] = "hello";
char string1[] = { 'h', 'e', 'l', 'l', 'o', '\0’ };
– Subscripting is the same as for a normal array
String1[ 0 ] is 'h'
string1[ 2 ] is 'l'
• Input from keyboard
char string2[ 10 ];
cin >> string2;
– Takes user input
– Side effect: if too much text entered, data written
beyond array
Passing Arrays to Functions
• Specify the name without any brackets
– To pass array myArray declared as
int myArray[ 24 ];
to function myFunction, a function call would resemble
myFunction( myArray, 24 );
– Array size is usually passed to function
• Arrays passed call-by-reference
– Value of name of array is address of the first element
– Function knows where the array is stored
• Modifies original memory locations
• Individual array elements passed by call-by-value
– pass subscripted name (i.e., myArray[ 3 ]) to function
Passing Arrays to Functions
• Function prototype:
void modifyArray( int b[], int arraySize );
Column subscript
Array name
Row subscript
• Initialize 1 2
3 4
int b[ 2 ][ 2 ] = { {1, 2}, {3, 4}};
1 0
– Initializers grouped by row in braces
3 4
int b[ 2 ][ 2 ] = { { 1 }, { 3, 4 } };
Multiple-Subscripted Arrays