J Mei J Mei - 1 month ago 4x
C Question

How to dynamically allocate memory for a struct with an unknown size?

So I want to allocate memory for a struct but I am new to C and have no clue on how to allocate it. The struct of have consists of 2 ints, 1 char, 1 bool(could be changed to int), and 2 doubles. I am to read or input a file and store the information from that file into the struct but the amount of information from the file may change. So what would be the best way to create the necessary space for it?


Use malloc and sizeof.

struct your_struct *s = malloc(sizeof(*s));