Lesson 13 of 31

Arrays

Arrays

An array is a fixed-size collection of elements of the same type, stored contiguously in memory.

Declaration and Initialization

int nums[5] = {10, 20, 30, 40, 50};
int zeros[100] = {0};  // all elements initialized to 0

Photon torpedo banks: indexed, loaded, and ready to launch in order. Torpedo tubes[0] through tubes[n-1].

Accessing Elements

Array indices start at 0:

int first = nums[0];   // 10
int third = nums[2];   // 30
nums[4] = 99;           // modify last element

Iterating

int nums[5] = {10, 20, 30, 40, 50};
for (int i = 0; i < 5; i++) {
    printf("%d\n", nums[i]);
}

sizeof

sizeof returns the total size in bytes. To get the number of elements:

int nums[5] = {10, 20, 30, 40, 50};
int count = sizeof(nums) / sizeof(nums[0]);  // 5

Warning: This trick only works on actual arrays, not on pointers. When you pass an array to a function, it decays to a pointer, so sizeof(arr) inside the function gives the pointer size (e.g., 8 bytes on 64-bit), not the array size. Always pass the length as a separate parameter.

No Bounds Checking

C does not check array bounds. Accessing nums[10] when the array has 5 elements is undefined behavior -- it will read whatever memory happens to be there.

Your Task

Write a function int sum_array(int *arr, int len) that returns the sum of all elements in the array. Use it to print the sum of {2, 4, 6, 8, 10}.

TCC compiler loading...
Loading...
Click "Run" to execute your code.