so I currently have a struct that looks like this:
typedef struct example {
bool arr[]; //i would like this to be an array of booleans,
//but i don't know the size right now; this is
//probably wrong
} example_t;
I also have a create function that looks like this:
example_t *newExample(int SIZE){
example_t *example = malloc(sizeof(example_t));
//initialize arr to a bool array of size SIZE, ideally all false!
example->arr = ???
return example;
}
And from this, I would be able to do something like:
example_t *example = newExample(MAX);
if ( example->arr[10] )
....
Is this possible in C, to create a variable sized array of booleans?
For Reference: I need someway to map integers to either a char*
or bool
, so I can call arr[num]
and be able to get either a string/word or a true/false value. Both ways, I'm not sure how to declare, and then initialize with a variable size. Thanks in advance!
In C99 you can use flexible array members where the last member can be an array without a given dimension, but there must be at least 2 members in the struct
.
You can use a pointer (here I am using int
instead of bool
for brevity):
#include <stdlib.h>
#include <stdio.h>
typedef struct example {
int *arr;
} example_t;
static example_t *newExample(size_t SIZE)
{
example_t *example = malloc(sizeof(example_t) + sizeof(int) * SIZE);
example->arr = (int *)(example + 1);
example->arr[5] = 5;
return example;
}
int main(void)
{
example_t *x = newExample(10);
printf("%d\n", x->arr[5]);
free(x);
return 0;
}
But this doesn't make much sense, why not add a first member containing the number of elements?
#include <stdlib.h>
#include <stdio.h>
typedef struct example {
size_t size;
int arr[];
} example_t;
static example_t *newExample(size_t SIZE)
{
example_t *example = malloc(sizeof(example_t) + sizeof(int) * SIZE);
example->size = SIZE;
example->arr[5] = 5;
return example;
}
int main(void)
{
example_t *x = newExample(10);
printf("%d\n", x->arr[5]);
free(x);
return 0;
}
Using this method haves an advantage: you can pass the object to any function without passing an extra parameter for the size.
You can do this by adding extra memory after example:
size_t boolsize = 10 * sizeof(bool);
struct example *ptr = malloc(sizeof *ptr + boolsize);
This way you call malloc only once and memory is layed out contiguously
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With