Last Updated on 2021-04-29 by Clay
Array is a data storage format in which data is stored in continuous memory space; that is the memory locations between each element are adjacent.
In C programming language, we can declare a variable to represents the entire array. For example, the format x[10]
means that there are 10 records stored in the x array, and the index are from 0 to 9.
Declare Array
dataType arrayName[arraySize]
When we declaring the array, we can also initialize the value of the array. (Of course, it is okay not to initialize.)
In addition to one-dimensional array, we can also declare two-dimensional, three-dimensional ... to N-dimensional array.
#include <stdio.h> int main() { // Init int x[3] = {1, 2, 3}; int y[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; int z[] = {1, 2, 3, 4, 5, 6, 7, 8}; return 0; }
The length of the z array depends on the number of elements declared in the back. This is also a common method of declaration.
Print the elements of array
If you want to print the elements of array, you need to use sizeof()
to calculate the length of array.
The reason for obtaining the length of the array is because in addition to the array declared by ourselves, sometimes we may also obtain an array of unknown length, such as the array elements returned from an external library.
if you want to use the for-loop to print the array elements step by step, you need to know the length of the array.
#include <stdio.h> int main() { // Init int x[] = {1, 2, 3, 4, 5, 6, 7, 8}; // Print x array for (int i=0; i<(sizeof(x)/sizeof(x[0])); ++i) { printf("%d\n", x[i]); } return 0; }
Output:
1
2
3
4
5
6
7
8
References
- https://stackoverflow.com/questions/37538/how-do-i-determine-the-size-of-my-array-in-c
- https://www.programiz.com/c-programming/c-arrays