-1

I'm doing a program in C, the program reads a file, in that file, the program finds X "elements", sometimes they are 3, sometimes 4... For each element it has to create a struct that I'm going to change the values during the program, but I need them to be initialized.

The problem is that I don't know if it's possible to initialize X structs without knowing how many I'm going to need (it depends on the file), and if it's possible I don't know how to do it...

Mr. User
  • 14
  • 2
  • Sure, if you know you have a max of `4` declare and array of struct `[4]`, if not sure but know it's definitely less than `20` declare `20` (and keep a counter of how many you actually fill). If you have no clue, declare a *pointer to struct* and dynamically allocate space for `4` of them with e.g. `malloc` and then `realloc` and resize the associated storage to hold as many as required. Just search this site for **dynamic memory allocation struct** and you will find hundreds of examples. – David C. Rankin Apr 14 '17 at 22:32
  • And, this site is more of a "I've been trying to do X with this code and I just can't make it work, where am I going wrong?" site. So, welcome to Stack Overflow. Please read the [**About**](http://stackoverflow.com/tour) page soon and also visit the links describing [**How to Ask a Question**](http://stackoverflow.com/questions/how-to-ask) and [**How to create a Minimal, Complete, and Verifiable example**](http://stackoverflow.com/help/mcve). Providing the necessary details, including your code, and associated errors, if any, will allow everyone here to help you with your question. – David C. Rankin Apr 14 '17 at 22:36

1 Answers1

1

If n is the number of structs you need and

struct s{
        int a;
        int b;
};

is your struct, then

struct s* X = calloc(n, sizeof(struct s));

allocates enough memory for n structs.

You can change the k-th entry like this:

(X + k)->a = 5;

or

X[k].a = 5;