Skip to Content
Course content

35: Working with One-Dimensional Arrays

Click on the "Edit" button in the top corner of the screen to edit your slide content.

I've seen this happen to almost every developer I've mentored: you create an array, you pass it into a function, and then you try to use sizeof inside that function to figure out how many elements are in the array. It feels intuitive. You're thinking, "The array is an object; it should know how big it is."

The Myth: Arrays Carry Their Own Size With Them

Let's look at why that intuition will lead you straight into a segmentation fault or a very confusing bug. Take a look at this snippet:

#include 

void print_size(int scores[]) {
    printf("Size inside function: %zu\n", sizeof(scores));
}

int main() {
    int my_scores[5] = {90, 85, 70, 95, 80};
    printf("Size in main: %zu\n", sizeof(my_scores));
    print_size(my_scores);
    return 0;
}

If you're on a 64-bit system, you'd expect the second print to also say 20 (5 integers * 4 bytes). Instead, it will print 8. Why? Because in C, when you pass an array to a function, it "decays" into a pointer to its first element. Inside print_size, scores isn't an array anymore; it's just a memory address. sizeof(scores) is returning the size of the pointer, not the buffer.

The Truth: You Are the Bookkeeper

In C, the language doesn't track the bounds of your array for you. There is no array.length property like you'll find in Java or Python. You are entirely responsible for keeping track of how many elements you've allocated. If you tell C to look at index 10 of a 5-element array, it will happily go to that memory location and read whatever garbage happens to be there—or crash your program if that memory belongs to something else.

The standard pattern for handling this is to always pass the size as a separate argument. It's a bit tedious, but it's the only way to be safe. Here is how we actually handle a collection of data, like a week's worth of temperature readings:

#include <stdio.h>

void analyze_temps(float temps[], int length) {
    float sum = 0;
    for (int i = 0; i < length; i++) {
        sum += temps[i];
    }
    printf("Average Temp: %.2f\n", sum / length);
}

int main() {
    float weekly_temps[] = {72.5, 75.0, 68.2, 70.1, 74.4, 78.9, 71.0};
    // We calculate length here, while the array hasn't decayed yet
    int num_days = sizeof(weekly_temps) / sizeof(weekly_temps[0]);
    
    analyze_temps(weekly_temps, num_days);
    return 0;
}

Notice the sizeof(weekly_temps) / sizeof(weekly_temps[0]) trick. This divides the total byte size of the array by the size of a single element, giving you the element count. I use this constantly, but remember: this only works in the scope where the array was originally declared.

One last thing to keep in mind: the "Off-by-One" error. Since C uses zero-based indexing, an array of size 10 has indices from 0 to 9. If your loop condition is i <= 10, you've just stepped out of bounds. It's a tiny mistake that causes massive headaches. Always use i < length.




📋 Practical Task

Exercise: Filtering High-Score Thresholds

You are building a leaderboard system for a game. Write a program that does the following:

  • Declare an integer array containing 10 random game scores (e.g., {450, 120, 800, 310, 900, 150, 600, 200, 850, 400}).
  • Create a function called count_high_scores that takes the array, the size of the array, and a threshold value (an integer).
  • The function should return the number of scores that are strictly greater than the threshold.
  • In main, call this function using a threshold of 500 and print the result.

Constraint: Ensure your function does not use sizeof to determine the array length; rely entirely on the size parameter you pass in.

Rating
0 0

There are no comments for now.

to be the first to leave a comment.