2020-08-09

array literals in c

sometimes it would be useful to assign array content literally by listing the contents. in most script languages one can do something like this:

a = [1, 2, 3, 4]

but c poses restrictions to that and the following lists some possible options.

option: stack arrays with literal initializer

example:

int a[3] = {1, 2, 3};
  • can only be used once where a variable is defined
  • can only be used for stack arrays, not for heap arrays
  • can be passed to subfunctions
  • can not be used in the parent of the allocating function
  • if the array is in a struct, the struct has to be stack allocated or the struct declaration uses only a pointer and the array is initialized separately
  • #include can be used to keep definitions in a separate file and load that into scope

option: functions as array literal expressions

int* ints4(a, b, c, d) {
  int* x = malloc(4 * sizeof(int));
  if (!x) return 0;
  x[0] = a;
  x[1] = b;
  x[2] = c;
  x[3] = d;
  return x;
}
int* a = ints4(2, 3, 4, 5);

memory allocation can fail, therefore the question of how to handle the failure arises.

option: exit the program

this is the easiest option. inside the array creator function:

if (!x) exit(1);

option: macro that checks the result and uses goto

  • needs a temporary variable and local goto label
x = ints4(1, 2, 3, 4) ? x : goto exit;

option: macro that sets values

  • array must have been declared and allocated beforehand
  • is not an expression that returns an array
#define int4(x, a, b, c, d) x[0] = a; x[1] = b; x[2] = c; x[3] = d;
int* x = malloc(4 * sizeof(int));
if (!x) exit(1);

ints4(target, 2, 3, 4, 5);