How can we use strlen in C language to calculate the length of an array?

When using the strlen function to calculate the length of an array, it is important to pass the array as a parameter to the function. However, it is crucial to note that the strlen function is used to calculate the length of a string, which is the length of a character array, and not the length of a general array.

To calculate the length of a regular array, you can achieve it by the following method:

#include <stdio.h>

int main() {
    int arr[] = {1, 2, 3, 4, 5};
    int len = sizeof(arr) / sizeof(arr[0]);
    
    printf("数组的长度为:%d\n", len);
    
    return 0;
}

In the example above, by using the sizeof operator, you can obtain the total number of bytes occupied by an array, then by dividing it by the number of bytes per element, you can get the length of the array.

 

 

More tutorials

How can you determine the standard deviation in R?(Opens in a new browser tab)

Converting string to array in the Java programming language(Opens in a new browser tab)

How to Delete Elements from an Array in Java(Opens in a new browser tab)

How can Oracle extract a specific substring?(Opens in a new browser tab)

What are the parameters of the RPAD function in Oracle?(Opens in a new browser tab)

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds