View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
    View All
    View All
    View All
    View All
    View All
    View All
    View All

    How To Find the Length of an Array in C?

    Updated on 30/04/20254,101 Views

    The C programming language takes into consideration the capacity of an array, which is an assortment of objects of similar information type. While working with arrays, it very well may be useful to know their size or the number of articles they contain. 

    The length of an array in C is analyzed in this article utilizing different techniques, including the size of () administrator, pointer arithmetic, and looping structures. Developers who know all about these procedures might explore and keep up with clusters with confirmation. 

    Additionally ,the array is utilized to hold a gathering of components of similar information types in the C programming language. And it makes array in C an essential component of top-tier software development courses. There are a few strategies for computing the size or number of components in a cluster. In this article, numerous strategies are analyzed. 

    The capacity to store a few bits of similar information type in a solitary bordering block of memory is made conceivable by arrays, which are a key part of the C programming language. Tracking down an array's size, or the number of things it contains, is every now and again significant while working with them.

    For some exercises, for example, repeating over its individuals, leading calculations, or powerfully assigning memory, knowing the length of a cluster is fundamental. This article looks at a few methodologies, for example, the sizeof() administrator, pointer number juggling, and circling developments, to decide the length of an array in C. Developers may safely oversee and cycle across clusters by dominating these procedures. 

    Methods to Find the Length of an Array in C

    1. Using the sizeof() Operator To Find the Length of an Array in C

    In C, utilizing the sizeof() administrator is a standard method for getting an array length. To view a variable's or information type's size in bytes, utilize the sizeof() administrator. The length of a cluster might be determined by partitioning its absolute size by the size of every part. For more details, you should explore out article on operators in C

    Syntax:

    sizeof(array) / sizeof(array[0])  

    Example:

    #include <stdio.h> 
    int main() { 
        int numbers[] = {1, 2, 3, 4, 5}; 
        int length = sizeof(numbers) / sizeof(numbers[0]); 
        printf("Length of the array: %d\n", length); 
        return 0; 
    }  

    Output:

    Length of the array: 5 

    Explanation: 

    In this illustration, we declare a five-element integer array called numbers. We get the array's length by partitioning the cluster's general size (sizeof(numbers)) by the size of every component (sizeof(numbers[0])). We yield the result to the control center in the wake of putting away it in the length variable.

    The sizeof() administrator may likewise be utilized to find the size of a person array.

    Get ready to land a high-paying career with the following full-stack development courses: 

    C Program to Calculate the Length of Integer Array Using sizeof()

    #include <stdio.h>
    int main() { 
        int numbers[] = {1, 2, 3, 4, 5}; 
        int length = sizeof(numbers) / sizeof(numbers[0]); 
        printf("Length of the array: %d\n", length); 
        return 0; 
    }

    Output: 

    Length of the array: 5 

    Explanation: 

    This program to find length of array in C calculates the number of elements in an integer array using the sizeof operator. The array numbers is initialized with 5 integers. The total size of the array in bytes is obtained using sizeof(numbers), and the size of a single element is obtained using sizeof(numbers[0]). Dividing these gives the total number of elements in the array: 

    length = sizeof(numbers) / sizeof(numbers[0]);

    Since each int typically occupies 4 bytes, and the array has 5 integers, the total size is 20 bytes. Dividing by 4 gives a length of 5, which is then printed.

    This approach works only within the same scope where the array is declared, not when the array is passed to a function (as it decays to a pointer).

    C Program to Calculate the Length of Character Array Using sizeof()

    #include <stdio.h>
    int main() { 
        char name[] = "John Doe"; 
        int length = sizeof(name) / sizeof(name[0]); 
        printf("Length of the array: %d\n", length); 
        return 0; 
    }  

    Output: 

    Length of the array: 9 

    Explanation: 

    This program to find the length of an array in C calculates the total length of a character array using the sizeof() operator. The array name is initialized with the string "John Doe", which includes 8 visible characters plus a null terminator (\0), making the total size 9 bytes. 

    The expression sizeof(name) / sizeof(name[0]) divides the total size of the array by the size of one character to determine the number of elements in the array. As a result, the program outputs 9, which includes the null terminator used to mark the end of the string in C. 

    Also learn about the different kind of operators in C, such as: 

    2. Using Pointer Arithmetic To Find the Length of Array in C

    Pointer arithmetic is a different method for calculating an array's length. An array name in C might be considered a pointer to the array's most memorable component. We might count the quantity of things and ascertain the length by augmenting the pointer up until we hit the invalid person or the finish of the cluster.

    Syntax:

    int length = 0; 
    while (*array != '\0') { 
        length ; 
        array ; 
    }  

    Example:

    #include <stdio.h> 
    int main() { 
        int numbers[] = {1, 2, 3, 4, 5, 0}; 
        int length = 0; 
        int *ptr = numbers; 
        while (*ptr != 0) { 
            length ; 
            ptr ; 
        }
        printf("Length of the array: %d\n", length); 
        return 0; 
    }  

    Output:

    Length of the array: 5 

    Explanation: 

    In this example, we declare an integer array of numbers with six elements, including a terminating zero. We initialize a pointer ptr to point to the first element of the array. Using a while loop, we increment the pointer and the length variable until we encounter the terminating zero. Finally, we output the array's length to the console.

    Pointer arithmetic may also be used to determine the length of a character array.

    For a detailed understanding, explore our article on Pointers in C

    C Program to Calculate the Length of Integer Array Using Pointer Arithmetic

    #include <stdio.h> 
    int main() { 
        int numbers[] = {1, 2, 3, 4, 5, 0}; 
        int length = 0; 
        int *ptr = numbers; 

        while (*ptr != 0) { 
            length++; 
            ptr++; 
        } 

        printf("Length of the array: %d\n", length); 
        return 0; 
    }

    Output: 

    Length of the array: 5

    Explanation: 

    This corrected C program demonstrates how to find the length of an array in C using pointer arithmetic and a sentinel value. The integer array numbers is initialized with values {1, 2, 3, 4, 5, 0}, where the 0 acts as a marker to indicate the end of the valid data. A pointer ptr is assigned to the start of the array, and a while loop is used to traverse the array. 

    Within the loop, the pointer is advanced using ptr++ and a counter length is incremented until the sentinel value 0 is encountered. This method effectively counts the number of elements before the sentinel and shows one way to find the length of an array in C when its size isn't explicitly known.

    C Program to Calculate the Length of Character Array Using Pointer Arithmetic

    #include <stdio.h>
    int main() { 
        char name[] = "John Doe"; 
        int length = 0; 
        char *ptr = name; 
        while (*ptr != '\0') { 
            length++; 
            ptr++; 
        } 
        printf("Length of the array: %d\n", length); 
        return 0; 
    }

    Output: 

    Length of the array: 8

    Explanation: 

    This C program shows how to find the length of an array in C, specifically a character array, using pointer arithmetic. The array name is initialized with the string "John Doe", which contains 8 characters. A pointer ptr is assigned to the beginning of the array, and the while loop iterates through each character until it encounters the null terminator '\0'. 

    During each iteration, the pointer is advanced and the length variable is incremented. Once the loop ends, length holds the number of characters in the string, effectively calculating the length of the character array without including the null terminator.

    Additionally, also read about the Array of Pointers in C to gain deep insights about this topic. 

    3. Using a Loop To Find the Length of an Array in C

    The third approach includes utilizing a looping construct, like the for or while loop, to iterate over the array members and tally how many iterations there are until the array is finished. 

    Syntax:

    int length = 0; 
    for (int i = 0; array[i] != '\0'; i ) { 
        length ; 
    } 

    Before you start with the code examples, learn about the following: 

    Example:

    #include <stdio.h> 
    int main() { 
        int numbers[] = {1, 2, 3, 4, 5}; 
        int length = 0;  
        for (int i = 0; numbers[i] != 0; i ) { 
            length ; 
        } 
        printf("Length of the array: %d\n", length); 
        return 0; 
    }  

    Output:

    Length of the array: 5 

    Explanation: 

    In this illustration, we declare a five-element integer array called numbers. We traverse over the array using a for loop, increasing the length variable with each iteration until we reach the ending zero. Finally, we output the array's length to the console.

    Similar to this, a loop may be used to find the size of a character array.

    C Program to Calculate the Length of Integer Array Using a Loop

    #include <stdio.h>
    int main() { 
        int numbers[] = {1, 2, 3, 4, 5, 0}; 
        int length = 0; 
        for (int i = 0; numbers[i] != 0; i++) { 
            length++; 
        }
        printf("Length of the array: %d\n", length);
        return 0; 
    }

    Output: 

    Length of the array: 5

    Explanation: 

    This program demonstrates how to find the length of an array in C using a simple for loop and a sentinel value. The integer array numbers is initialized with five values followed by a 0, which acts as a stopping point. Further, the loop iterates through the array, checking each element until it encounters the sentinel. In each iteration, the length variable is incremented to count the elements. 

    This technique allows the program to determine the length of the array without using sizeof() or explicitly specifying the size, as long as the array ends with a known sentinel value.

    C Program to Calculate the Length of Character Array Using a Loop

    #include <stdio.h> 
    int main() { 
        char name[] = "John Doe"; 
        int length = 0;
        for (int i = 0; name[i] != '\0'; i++) { 
            length++; 
        } 
        printf("Length of the array: %d\n", length); 
        return 0; 
    }

    Output: 

    Length of the array: 8 

    Explanation: 

    This corrected program shows how to find the length of an array in C using a for loop, specifically for a character array. The array name is initialized with the string "John Doe", which contains 8 characters followed by a null terminator ('\0'). The loop iterates through each character of the array until it encounters the null terminator. 

    In addition, during each iteration, the loop counter “I” is incremented, and the length variable keeps track of how many characters have been counted. This method effectively calculates the length of the string without including the null terminator. 

    Conclusion

    All in all, while working with arrays in C, sorting out a cluster's length is a basic activity. The sizeof() administrator, pointer number-crunching, and circles were the three methodologies that were inspected in this article to decide the length of a cluster. By isolating the whole size of the array by the size of every individual component, the sizeof() administrator offers a straightforward technique for computing the length. Utilizing pointer number-crunching, we might circle through the cluster until we arrive at the invalid person or the finish of the array by treating the array name as a source of perspective to the principal component. Circles, similar to the for or while circle, cycle over the things of a cluster and monitor the quantity of emphasis until the array's end is reached.

    Each approach has its advantages, and the decision of approach depends on the specific program needs. Understanding these strategies enables C developers to exactly work out an array's length and productively use arrays to do various errands. This article likewise resolved regularly posed inquiries about ascertaining the length of string array in C, including how to utilize the sizeof() administrator for character clusters, the differentiation between working out the length of number and character arrays, how to powerfully distribute memory utilizing the array length, and different methodologies. Developers may safely work with arrays in C by utilizing these methodologies, which ensure exact calculations and powerful control of cluster things.

    FAQs

    1. How do you find the length of an array in C?

    You can find the length of an array in C using methods like the `sizeof()` operator or by iterating through the array with a loop. For character arrays, a common approach is to use the null terminator `'\0'` to indicate the end, while for integer arrays, you might use a sentinel value or pointer arithmetic.

    2. What is the purpose of the null terminator in C strings?

    The null terminator `'\0'` marks the end of a C-style string. It helps functions like `strlen()` and `printf()` know where the string ends, preventing them from reading beyond the allocated memory. Without it, these functions would keep reading memory, potentially causing undefined behavior or errors.

    3. How does pointer arithmetic work in C?

    Pointer arithmetic involves manipulating pointers to navigate through arrays. You can increment or decrement a pointer to move to the next or previous array element. For example, `ptr++` moves the pointer to the next element, and `ptr--` moves it back. This is commonly used for iterating over arrays in C.

    4. What is the difference between an array and a pointer in C?

    An array in C is a fixed-size collection of elements, while a pointer is a variable that stores the memory address of another variable or array. Although arrays can be treated similarly to pointers in some contexts, arrays hold actual data, whereas pointers can point to any memory location and be reassigned.

    5. Why is `sizeof` used to determine the length of an array in C?

    The `sizeof` operator returns the size of a variable or data type in bytes. For an array, `sizeof(array)` gives the total number of bytes the array occupies in memory. To get the number of elements, divide by `sizeof(element)`, which gives the size of each element in the array.

    6. Can arrays be resized in C?

    No, arrays in C have a fixed size once they are declared. If you need to resize an array, you would typically use dynamic memory allocation with `malloc()` or `calloc()` and adjust the memory as needed. Alternatively, you can use data structures like linked lists or resizeable arrays in higher-level languages.

    7. What is the difference between `strcpy` and `strncpy` in C?

    `strcpy` copies a string from source to destination, including the null terminator, without checking bounds. `strncpy`, on the other hand, copies up to a specified number of characters, providing protection against buffer overflow. However, `strncpy` does not always null-terminate the destination string if the length exceeds the given size.

    8. How can you initialize a pointer to an array in C?

    To initialize a pointer to an array in C, you can assign the pointer the address of the first element of the array. For example, if you have an array `arr`, you can set `int *ptr = arr;`. This allows the pointer to traverse the array using pointer arithmetic or dereferencing.

    9. How do you manage memory for dynamic arrays in C?

    In C, dynamic arrays are managed using memory allocation functions like `malloc()`, `calloc()`, and `realloc()`. `malloc()` allocates memory, `calloc()` allocates and initializes memory to zero, and `realloc()` resizes a previously allocated block. Remember to free the memory with `free()` when it's no longer needed to avoid memory leaks.

    10. What is the significance of the `\0` character in C arrays?

    The `\0` character is a special null terminator used in C strings to mark the end of the string. Without it, functions that process strings would not know where the string ends, which can lead to undefined behavior or access to unintended memory locations. It is crucial for string handling in C.

    11. Can you pass an array to a function in C?

    Yes, in C, you can pass an array to a function by passing the array's name, which is equivalent to a pointer to its first element. This allows the function to access and modify the array elements. However, the size of the array must either be passed separately or inferred.

    image

    Take a Free C Programming Quiz

    Answer quick questions and assess your C programming knowledge

    right-top-arrow
    image
    Join 10M+ Learners & Transform Your Career
    Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
    advertise-arrow

    Free Courses

    Start Learning For Free

    Explore Our Free Software Tutorials and Elevate your Career.

    upGrad Learner Support

    Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

    text

    Indian Nationals

    1800 210 2020

    text

    Foreign Nationals

    +918068792934

    Disclaimer

    1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.

    2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.