Can I ‘extend’ a struct in C?

Evidently this feature has been added to C11, but alas I don’t have access to a C compiler of recent vintage (>= GCC 4.6.2). typedef struct foo { int a; } foo; typedef struct bar { struct foo; int b; } bar; int main() { bar b; b.a = 42; b.b = 99; return 0; … Read more

Initializing an object to all zeroes

memset is practically never the right way to do it. And yes, there is a practical difference (see below). In C++ not everything can be initialized with literal 0 (objects of enum types can’t be), which is why in C++ the common idiom is some_struct s = {}; while in C the idiom is some_struct … Read more

How to initialize a struct to 0 in C++

Before we start: Let me point out that a lot of the confusion around this syntax comes because in C and C++ you can use the = {0} syntax to initialize all members of a C-style array to zero! See here: https://en.cppreference.com/w/c/language/array_initialization. This works: // z has type int[3] and holds all zeroes, as: `{0, … Read more

C initialize array within structure

Here is my version: #include <stdio.h> struct matrix { int rows; int cols; int **val; } a = { .rows=3, .cols=1, .val = (int*[3]){ (int[1]){1}, (int[1]){2}, (int[1]){3} } }, b = { .rows=3, .cols=4, .val = (int*[3]){ (int[4]){1, 2, 3, 4}, (int[4]){5, 6, 7, 8}, (int[4]){9,10,11,12} } }; void print_matrix( char *name, struct matrix *m … Read more

Returning a struct pointer

Should I declare a Mystruct variable, define the properties of Mystruct, assign a pointer to it, and return the pointer Definitely not, because the variable defined in the function (in “auto” storage class) will disappear as the function exits, and you’ll return a dangling pointer. You could accept a pointer to a Mystruct (caller’s responsibility … Read more