part of c programming
sometimes it would be useful to assign array content literally by listing the contents. something like this is possible in most scripting languages:
a = [1, 2, 3, 4]
but c is limited, and the following shows some possible options and alternatives.
example:
int a[3] = {1, 2, 3};
this method can also be used to define nested arrays:
int a[3][2] = {{1, 2}, {3, 4}, {5, 6}};
int* ints4(int a, int b, int c, int 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* e = ints4(2, 3, 4, 5);
memory allocation can fail, therefore the question of how to handle this failure arises.
this interface is similar to malloc, which also just returns a null pointer on failure.
no error checking code is needed, or possible, with this option. it does not compose well because it exits the process that uses it, which tends to be particularly undesirable when the code is used as part of a library. inside the array creating function:
if (!x) exit(1);
needs a temporary variable and a local goto label
int* x = ints4(1, 2, 3, 4); if (!x) goto exit;
#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(x, 2, 3, 4, 5);