How to get the actual length of an array in the C language?
In C language, the length of an array is fixed and cannot be changed once defined. Therefore, ways to obtain the actual usage length of an array include:
- Keep track of the number of elements in the array by defining a variable to store the actual number of elements being used, and update this variable every time an element is added or removed. For example:
int arr[100]; // 假设数组最大长度为100
int length = 0; // 记录实际使用的元素个数
// 添加元素
arr[length] = 10;
length++;
// 删除元素
length--;
// 获取实际使用的元素个数
printf("实际使用的元素个数:%d\n", length);
- Use a specific value of an element as the end marker: Set a specific value (such as 0 or -1) as the end marker in the last element of the array, by iterating through the array to find the position of this end marker. For example:
int arr[] = {1, 2, 3, 4, 0}; // 数组最后一个元素为0作为结束标志
int length = 0;
while (arr[length] != 0) {
length++;
}
printf("实际使用的元素个数:%d\n", length);
- determine the length of a string
char arr[] = "hello";
int length = strlen(arr);
printf("实际使用的元素个数:%d\n", length);
It is important to note that all of the above methods are used to obtain the actual length of an array when the array is known. However, if the array is being passed to a function, it is typically necessary to also pass the array length as a parameter in order to determine the actual length within the function.