TIL: Initializing C objects
2022-05-18 00:00:00 +0000 UTCWhen working in C, there are a few ways to intialize objects. The simplest is the direct assignment:
int obj = 15;
size_t hash = 14695981039346656037ULL; // FNV offset basis constant
char* ptr = 0;
char a = 'a';
char* str = "a string";
For simple object types, you can just put a correctly formatted value on the righthand side of the =
assignment operator.
For fixed-length array types, there is another initializer syntax that uses curly braces:
int nums[3] = { 1, 2, 3 };
int nums[5] = { 1, 2, 3 }; // the remainder of the values are set to 0
int nums[5] = { // set to [0, 2, 0, 0, 3]
[1] = 2,
[4] = 3,
};
For structs, initializer syntax looks like:
struct A {
int B;
int C;
};
struct A a = {
.B = 1,
.C = 2,
};
struct A a2 = { 0 }; // sets all fields to 0; can be used for any object to set to its 0 value.
For variable length arrays or malloc’d arrays, intialization requires looping:
int* arr = malloc(sizeof(int)*10);
for (size_t i = 0; i < 10; i++) {
arr[i] = i;
}