array

I think this is one of the most common questions that I see when I look through stackoverflow’s C section (and one that I myself struggled with after I first started learning C). C is not like Java. There are no dedicated functions to calculate the length of an array. You can’t even declare an array without first specifying the length (so C can allocate the appropriate amount of memory on the stack).

Anyway, but back to the question at hand: How do you find the length of an array in C?Lets say I have an array of numbers 1 to 10 (i.e. an array of length 10). You would declare it at such:

int myArray[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

Now, let’s say you declare this in your main() function and then send it off to a function to use. How would the function know the length of your array if it didn’t declare it?

Here’s a simple way that works every time!:

// You have an array named myArray that has been passed into your function. 
// You do not know the length of the array, but you must return the last number in the array.
// To do this, you first find the length of the array, and then return myArray[length-1].
int function return_last_element(int myArray[]) {
    int length = sizeof(myArray) / sizeof(myArray[0]);
    return myArray[length-1];
}

And voila! You’re done! This approach will work for an array of any type.

There is another way to calculate the length of an int array:

int length = sizeof(myArray) / sizeof(int);

You divide the sizeof() value of your array by the sizeof value of the int (the type of your array). Both approaches should give you the same answer.

Aside: this post was inspired by my new C assignment that requires me to extract an array from a struct linked list and then iterate through it to find all instances when the stored value != 0. And that’s just the first part! I am kind of excited because this assignment has us building a simple query engine, which I’ve been meaning to learn how to do for the longest time. So, back to that I go!

Advertisements