C Arrays and Strings Guide
Short answer: a C array is a fixed-size block of elements of one type stored side by side in memory. A C string is not a special type: it is an array of char that ends with a null character ('\0'). Because C does not check bounds, you must track sizes yourself.
Declaring and initializing arrays
int scores[5]; // uninitialized (garbage values)
int primes[5] = {2, 3, 5, 7, 11}; // fully initialized
int zeros[5] = {0}; // all zero
int auto_size[] = {10, 20, 30}; // size 3, deduced
printf("%d\n", primes[2]); // 5
primes[0] = 13;
Indexes start at 0. Accessing primes[5] is out of bounds and has undefined behavior: it may crash, corrupt data or appear to work.
Looping and the size of an array
size_t count = sizeof primes / sizeof primes[0]; // 5
for (size_t i = 0; i < count; i++) {
printf("%d ", primes[i]);
}
This sizeof trick only works where the real array is in scope. Inside a function that receives the array, it gives the size of a pointer.
Passing arrays to functions
int sum(const int *values, size_t length) {
int total = 0;
for (size_t i = 0; i < length; i++) total += values[i];
return total;
}
int result = sum(primes, count);
An array passed to a function becomes a pointer to its first element, so the function must receive the length separately. Use const when the function must not modify the data. Understand why in pointers in C.
Two-dimensional arrays
int grid[2][3] = {
{1, 2, 3},
{4, 5, 6}
};
for (int r = 0; r < 2; r++) {
for (int c = 0; c < 3; c++) {
printf("%d ", grid[r][c]);
}
printf("\n");
}
Elements are stored row by row. When passing a 2D array to a function, the column count must be known: void print(int g[][3], int rows).
Strings
char name[] = "Asha"; // 5 bytes: 'A','s','h','a','\0'
char buffer[20] = "Hello"; // room for more characters
const char *msg = "Hi"; // pointer to a read-only literal
printf("%s\n", name);
printf("%zu\n", strlen(name)); // 4, the terminator is not counted
Always leave space for the terminating '\0'. Do not modify a string literal through a char *; declare it const char * or copy it into an array.
Useful functions from string.h
| Function | Purpose |
|---|---|
strlen(s) | Length without the terminator |
strcmp(a, b) | Compare: 0 means equal |
strncpy, strncat | Bounded copy and append (be careful with termination) |
strchr, strstr | Find a character or substring |
memcpy, memset | Copy or fill raw bytes |
Comparing and copying strings safely
// Wrong: compares addresses, not text
if (a == b) { ... }
// Right
if (strcmp(a, b) == 0) { ... }
// Safe formatted copy with a size limit
char dest[16];
snprintf(dest, sizeof dest, "%s", source);
snprintf never writes more than the buffer size and always terminates the result, which makes it a good default. Avoid gets (removed from the language) and be careful with strcpy and strcat, which do not check length.
Reading input safely
char line[100];
if (fgets(line, sizeof line, stdin)) {
line[strcspn(line, "\n")] = '\0'; // remove the newline
printf("You typed: %s\n", line);
}
Dynamic arrays
When the size is only known at run time, allocate with malloc and free later. Details and pitfalls are in memory management.
int *values = malloc(n * sizeof *values);
/* use values[0] .. values[n-1] */
free(values);
Common mistakes
- Writing past the end of an array (buffer overflow).
- Forgetting space for
'\0'in a string buffer. - Comparing strings with
==. - Using
sizeofon an array parameter inside a function. - Returning a pointer to a local array.
Next, model grouped data with structures and unions. New to C? Start with what C is.
FAQs
Can I resize a C array?
Not a fixed array. Use dynamic memory and realloc.
What is the difference between char name[] and char *name?
The first is a modifiable array that holds a copy of the text. The second is a pointer, often to read-only literal text.
Why does my string print garbage?
The terminating null is probably missing, so the function keeps reading past the end of the array.
Do C arrays know their length?
No. Always pass the length along with the array.
