Length vs Size of a string array
What you'll learn: You will learn how to distinguish between the physical memory capacity of an array and the actual number of characters currently forming a string within it.
The Suitcase Analogy
Imagine you have a suitcase designed to hold 10 shirts. This is the Size of your suitcase—its maximum capacity. However, you might only pack 3 shirts for a short trip. Those 3 shirts represent the Length of your contents.
In C, a character array works exactly like this suitcase. You must define a fixed capacity (Size) when you create the array, but the actual text you store inside it (Length) can be much smaller.
Size: The Capacity
The size of an array is the total number of bytes allocated in memory. If you declare char myString[20];, the size is 20. This space is reserved for you as soon as the program runs, whether you fill it with letters or leave it empty. In C, you use the sizeof() operator to find this value.
Length: The Content
The length of a string is the number of visible characters it contains, excluding the hidden null terminator (\0). C knows where a string ends because it looks for that null terminator. If your 20-slot array contains the word "Apple", the length is 5. We use the strlen() function (from the <string.h> library) to find this value.
Seeing it in Code
Here is how these two concepts look side-by-side in a program:
#include <stdio.h>
#include <string.h>
int main() {
// We reserve 20 slots of memory (Size)
char city[20] = "Tokyo";
// Sizeof returns the total memory capacity
printf("Total Size: %zu bytes\n", sizeof(city));
// Strlen returns the number of characters before the \0
printf("String Length: %zu characters\n", strlen(city));
return 0;
}
In this example, sizeof(city) will be 20, because that is how much room you requested. However, strlen(city) will be 5, because "Tokyo" only occupies five slots.
Why it Matters
Confusing these two can lead to bugs. If you try to copy a string of length 30 into an array of size 20, your program will crash or behave unpredictably because you are trying to fit 30 shirts into a 10-shirt suitcase. Always ensure your Size is at least Length + 1 (to account for the null terminator).
Key takeaway
Size is the total memory capacity of the array, while Length is the number of characters currently stored in it.