Arrays & C Strings
Prev: Control Flow & Functions | Up: fundamentals | Next: Structs, Unions & Enums
Rel: Pointers & Pointer Arithmetic, stdlib & string.h
Ref: cppreference — C Arrays
Tags: #public #prog #c #fundamentals #strings
Contents
Array-to-Pointer Decay
In most expressions (including passing to a function), an array int a[10] decays to a pointer to its first element (int *), losing its length. Always pass (const T *ptr, size_t len) together:
#include <stddef.h>
static int sum_array(const int *arr, size_t len) {
int total = 0;
for (size_t i = 0; i < len; i++) {
total += arr[i];
}
return total;
}
Within the defining scope only (before decay), element count is sizeof(a) / sizeof(a[0]).
NUL-Terminated C Strings
A C string is a char array terminated by a '\0' byte. String literals ("hello") live in read-only memory — always bind them to const char *.
strlen(s)scans in $O(n)$ up to'\0'(excluding'\0').- Allocate
strlen(s) + 1bytes when copying. - Prefer
snprintf(dst, sizeof(dst), "%s", src)over unsafestrcpy/sprintf.
Linked from
- tuts/c/builtins/char
- tuts/c/builtins/sizeof
- tuts/c/fundamentals
- tuts/c/fundamentals/arrays_and_strings
- tuts/c/fundamentals/control_flow_and_functions
- tuts/c/fundamentals/structs_unions_and_enums
- tuts/c/pointers_and_memory/pointers_and_pointer_arithmetic
- tuts/c/stdlib/ctype
- tuts/c/stdlib/ctype/isalpha
- tuts/c/stdlib/ctype/isdigit
- tuts/c/stdlib/ctype/isspace
- tuts/c/stdlib/ctype/tolower
Related notes
- tuts/c/fundamentals Linked here; links to this page; shared tags: #c, #fundamentals, #prog
- tuts/c/fundamentals/control_flow_and_functions Linked here; links to this page; shared tags: #c, #fundamentals, #prog
- tuts/c/fundamentals/structs_unions_and_enums Linked here; links to this page; shared tags: #c, #fundamentals, #prog
- tuts/c/pointers_and_memory/pointers_and_pointer_arithmetic Linked here; links to this page; shared tags: #c, #prog
- tuts/c/builtins/char links to this page; shared tags: #c, #prog
- tuts/c/builtins/sizeof links to this page; shared tags: #c, #prog
- tuts/c/stdlib/ctype links to this page; shared tags: #c, #prog
- tuts/c/stdlib/ctype/isalpha links to this page; shared tags: #c, #prog
- tuts/c/stdlib/ctype/isdigit links to this page; shared tags: #c, #prog
- tuts/c/stdlib/ctype/isspace links to this page; shared tags: #c, #prog