Beginner · Functions and arrays · topic 14 of 60 · 25 min
Arrays
Explanation
Declaring and initialising
int marks[5]; /* 5 ints, uninitialised if local (garbage) */
int prices[] = {499, 120, 2999}; /* size 3 worked out from the initialiser */
int zeros[100] = {0}; /* all 100 elements set to 0 */
double temps[7] = {31.5, 33.0}; /* first two set, the remaining five are 0.0 */
int days[12] = { [1] = 28 }; /* C99 designated initialiser: element 1 is 28, others 0 */
marks[0] = 78;
marks[4] = 91; /* valid indexes: 0 to 4 */Arrays in memory
int a[4] = {10, 20, 30, 40};
address element value
0x1000 a[0] 10
0x1004 a[1] 20 (each int is 4 bytes here)
0x1008 a[2] 30
0x100C a[3] 40Counting elements
int prices[] = {499, 120, 2999, 75};
size_t n = sizeof prices / sizeof prices[0]; /* 16 / 4 = 4 */
for (size_t i = 0; i < n; i++) printf("%d\n", prices[i]);Passing arrays to functions
int sum(const int a[], size_t n) { /* a is really a pointer: const int *a */
int total = 0;
for (size_t i = 0; i < n; i++) total += a[i];
return total;
}
void apply_discount(int a[], size_t n, int percent) { /* no const: it changes the caller's array */
for (size_t i = 0; i < n; i++) a[i] -= a[i] * percent / 100;
}
int main(void) {
int prices[] = {500, 200, 1000};
size_t n = sizeof prices / sizeof prices[0];
apply_discount(prices, n, 10); /* prices is now {450, 180, 900} */
printf("%d\n", sum(prices, n)); /* 1530 */
return 0;
}An array is not copied when passed; the function receives the address of the first element (the array "decays" to a pointer, module 5). So the function can change the caller's elements, and inside the function sizeof a gives the size of a pointer (8), not of the array. That is why you always pass the length separately. Mark parameters const when the function only reads.
Arrays cannot be assigned
int b[3] = a; and b = a; do not compile. Copy element by element in a loop, or with memcpy(b, a, sizeof a) from <string.h>. Comparing with a == b compares addresses, not contents.
Need help?
Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.
Try:
Watch the lesson
Arrays · 1/6
In this lesson you will store many values in a C array.
Prefer a video by a teacher? Find free videos on “c arrays tutorial passing arrays to functions sizeof bounds” on YouTube ↗
In real life: Monthly sales in a shop
A small shop's program stores 12 monthly sales figures in an array, finds the best month and the total, and passes the array with its length to helper functions.
#include <stdio.h>
int best_month(const int sales[], int n) {
int best = 0;
for (int i = 1; i < n; i++) if (sales[i] > sales[best]) best = i;
return best;
}
int main(void) {
int sales[12] = {42, 38, 51, 47, 60, 55, 49, 52, 58, 71, 83, 64}; /* in thousands of rupees */
int m = best_month(sales, 12);
printf("Best month: %d (Rs %d thousand)\n", m + 1, sales[m]); /* Best month: 11 (Rs 83 thousand) */
return 0;
}Practice (0/3 done)
What does this print? int a[5] = {1, 2}; printf("%d %d\n", a[1], a[4]);
Inside void f(int a[]) on a 64-bit Linux system, sizeof a is…
Write a program with an array of 10 temperatures. Write functions to compute the average (const array parameter), find the index of the maximum, and count readings above a threshold. Then write a function that converts every reading from Celsius to Fahrenheit in place (non-const parameter). Print the array before and after.
Quick quiz
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- 2D arrays and classic array algorithmsFunctions and arrays · same module
- Scope and storage classesFunctions and arrays · same module
- Pointers and arraysPointers
- ArraysJava Programming (Core to Spring Boot) · Arrays and strings
- Arrays: one name, many valuesC# and .NET · Arrays, strings and null
- Arrays, std::array and a first look at std::vectorC++ Programming (modern C++ and DSA) · References, pointers, arrays and strings
Questions people ask about this
Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.
What is the index of the last element of int a[10]?
Answer: 9
Indexes run from 0 to 9.
Which copies array a (3 ints) into array b?
Answer: memcpy(b, a, sizeof a);
Arrays cannot be assigned; copy the bytes or loop.
Does C check array bounds at run time?
Answer: No: out-of-bounds access is undefined behaviour
Use sanitizers when testing.
int a[] = {4, 5, 6, 7}; What is sizeof a / sizeof a[0]?
Answer: 4
Total bytes divided by bytes per element.
Where does an array NOT decay to a pointer?Related
How do you get the length of an array arr?Related
What is the index of the last item in an array of length 8?Related
What is the index of the LAST element of an array of size 10?Related
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.
Next steps
- 1 more topic in “Functions and arrays” before its exam: 2D arrays and classic array algorithms.
- Module 3 exam: Functions and arrays · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
- Then the next module, Strings in C. 60 topics left in the course before the final exam.