sizeof just cares about the type of its argument. b[0] or *b are both of type bool, so it's the same as saying sizeof(bool). We prefer saying sizeof *b (or as laserlight prefers, sizeof b[0], presumably to emphasize to the reader that it's an array) because that way if we want to change the type we can do it in only one place.
The OS will clean up the memory when the process ends, so you don't actually need to free the array. It's considered good practice, though.
If you want to read and write your bools as chars then you can either just use chars in the first place or do the conversion. So if you are reading T's and F's from a file into a bool array you would need to convert:
Example input file:
Code:
15
T F F T F F F T F F T T T F F
Code:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
bool *read_bool_array(const char *filename, int *size) {
FILE *fin = fopen(filename, "r");
if (!fin) {
perror("fopen");
exit(EXIT_FAILURE);
}
fscanf(fin, "%d", size);
bool *b = malloc(*size * sizeof *b);
if (!b) {
perror("malloc");
exit(EXIT_FAILURE); // OS will close file
}
for (int i = 0; i < *size; ++i) {
char ch;
fscanf(fin, " %c", &ch); // the space before %c causes it to skip whitespace
b[i] = (ch == 'T' || ch == 't'); // considering non-T's as F's
}
fclose(fin);
return b;
}
void print_bool_array(const bool *b, int size) {
for (int i = 0; i < size; ++i)
printf("%2d ", i);
putchar('\n');
for (int i = 0; i < size; ++i)
printf(" %c ", b[i] ? 'T' : 'F');
putchar('\n');
}
int main() {
int size;
bool *b = read_bool_array("bools.txt", &size);
print_bool_array(b, size);
free(b);
return 0;
}