J Mei J Mei - 11 months ago 54
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?

Answer Source

Use malloc and sizeof.

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