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];
}
CodePudding user response:
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;
}
CodePudding user response:
The flexible array must be the last member in the struct. 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 {
int 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;
}
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);
}
