How to get the Length of an Array in C
Table of Contents
In this post, we'll learn how to get the length of an array in C.
Unfortunately, C does not have a built-in function to get the length of an array. This means we'll have to write some code that does this for us.
Using sizeof()
The easiest way to get the length of an array is to use the sizeof()
function. This function returns the size of whatever is passed in, in bytes.
The logic here is that to get the number of elements in an array, we can just divide the size of the entire array by the size of a single element.
Here's an example of how to use sizeof()
to get the length of an array in C:
CLIKEint array[] = { 0, 1, 2 };
int length = sizeof(array) / sizeof(array[0]);
printf("%u", length);
// 3
In other words, the length of the array is equal to the size of the entire array, divided by the size of a single element.
Here is a more fleshed-out example:
CLIKEint array[] = { 0, 1, 2 };
int arraySize = sizeof(array);
int elementSize = sizeof(array[0]);
int length = arraySize / elementSize;
printf("%u", length);
// 3
Conclusion
We've seen how to get the length of an array in C using sizeof()
. Hopefully, this post has been helpful to you.
Happy coding!
- How to build a Discord bot using TypeScript
- How to deploy a MySQL Server using Docker
- How to deploy an Express app using Docker
- How to deploy a Node app using Docker
- How to Scrape the Web using Node.js and Puppeteer
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Getting User Location using JavaScript's Geolocation API
- Getting Started with Moment.js
- Learn how to build a Slack Bot using Node.js
- Creating a Twitter bot with Node.js
- Setting Up Stylus CSS Preprocessor
- Setting Up a Local Web Server using Node.js