Store a sequence or a rectangular table
An array contains a fixed number of elements of the same type in contiguous storage. A one-dimensional array suits a list of marks; a two-dimensional array suits a fixed-size table. C does not automatically check array bounds.
Initialize and traverse a list
#include
int main(void) {
int marks[] = {62, 75, 83, 90};
size_t length = sizeof marks / sizeof marks[0];
int total = 0;
for (size_t i = 0; i < length; ++i) {
total += marks[i];
}
printf("total=%d average=%.2f\n", total, (double)total / length);
return 0;
} Expected output: total=310 average=77.50. The valid indices are 0 through 3. marks[4] is outside the array. In this small example the total fits int; larger applications must also choose an accumulator that cannot overflow.
Dimensions and initialization
int grid[2][3] = {
{1, 2, 3},
{4, 5, 6}
};This is an array of two rows, each containing three ints. grid[1][2] is 6. C stores rows contiguously in row-major order. To print the table, use an outer row loop and an inner column loop. A declaration such as int values[5] = {1, 2}; initializes the remaining elements to zero; a local array with no initializer does not receive that guarantee.
Passing arrays to functions
In a parameter declaration, int values[] is adjusted to a pointer parameter. The callee does not receive the array's length automatically. Pass the element count separately. Inside that function, sizeof values gives the pointer size, not the size of the caller's array. For a fixed-width matrix, the row width is needed so the compiler can locate the next row.
int sum3(const int row[3]) {
return row[0] + row[1] + row[2];
}This fragment assumes the caller supplies at least three valid elements and that their sum is representable. The notation does not make a runtime bounds check.
Exercises with expected results
- Find the largest value in marks. Initialize the candidate from marks[0], then compare the remaining elements. Answer: 90.
- Find the sum of the first row of grid. Answer: 6.
- Transpose a 2-by-3 matrix into a separate 3-by-2 array using
out[column][row] = grid[row][column]. - Why does a loop using
i <= lengthfail? Its last iteration accesses one element beyond the array.
हिन्दी संकेत: length और last index अलग हैं। Function को pointer के साथ length भी दें।