part of c programming
this document describes how initial array contents can be expressed in c. it complements "array representations" by focusing on construction syntax and initialization forms, not storage models or mutation semantics.
c does not have array values in the abstract sense. it has objects with storage duration that may be initialized using literal syntax. all mechanisms described below operate within that constraint.
literal syntax therefore always implies
a concrete object
a defined storage duration
a fixed element type
int a[] = {1, 2, 3};
int b[3][2] = {
{1, 2},
{3, 4},
{5, 6}
};int *a = (int[]){1, 2, 3, 4};storage duration
commonly used to
initialize pointers
pass literal arrays to functions
void print_array(int *a, size_t n);
print_array((int[]){1, 2, 3, 4}, 4);heap-allocated arrays cannot be initialized directly
literal syntax can only produce temporary or static objects
common pattern
allocate
copy from a literal source
int *a = malloc(4 * sizeof(int));
memcpy(a, (int[]){1, 2, 3, 4}, 4 * sizeof(int));typedef struct {
int data[3];
} int_array3_t;
int_array3_t x = { .data = {1, 2, 3} };x.data[1];
typedef struct {
size_t size;
int data[];
} int_array_t;#define int_array(...) ((int[]){__VA_ARGS__})
int *a = int_array(1, 2, 3, 4);advantages
limitations
type is fixed or implicit
debugging and error reporting are weaker
semantics depend on expansion context
#define new_array(size, ...) ({ \
int *_a = malloc(size * sizeof(int)); \
if (_a) { \
int _t[] = {__VA_ARGS__}; \
memcpy(_a, _t, size * sizeof(int)); \
} \
_a; \
})int *int_array4(int a, int b, int c, int d);
int *new_array(size_t n, ...);