Is something like this possible in C? It would be really nice to have both of these.
typedef struct {
int r;
char a0[0];
char a1[0];
}
No. Rather use dynamically allocated memory. Something like:
typedef struct {
int *data1;
size_t len1
int *data;
size_t len2;
} sometype;
sometype *alloc_sometype(size_t len1, size_t len2) {
sometype *n = malloc(sizeof(sometype));
if (!n) return NULL;
n->len1 = len1;
n->len2 = len2;
n->data1 = malloc(sizeof(int) * len1);
n->data2 = malloc(sizeof(int) * len2);
// Error handling if those malloc calls fail
return n;
}
The flexible array must be the last member in the struct so you can't have two. However, if both arrays are supposed to have the same size, you could combine them:
#include <stdio.h>
#include <stdlib.h>
typedef struct { // a struct to keep one a0 a1 pair
char a0;
char a1;
} A;
typedef struct {
size_t len;
A a[]; // flexible array of a0 a1 pairs
} data;
data *data_create(size_t len) {
data *d = malloc(sizeof *d + len * sizeof *d->a);
if(d) d->len = len;
return d;
}
int main() {
data *d = data_create(10);
for(size_t i = 0; i < d->len; ++i) {
d->a[i].a0 = i;
d->a[i].a1 = i+1;
}
free(d);
}
[], not[0]. If you need to have multiple arrays of lengths determined at run-time “in” a structure, use pointers (and set esch to point to memory allocated for its array).[0]is a GCC extension.