1

Trying to create a struct that contains three arrays. I'm unsure of how large to make the arrays until the input is read.

How can i initialize these arrays in the struct if i'm unsure how large they are going to be in the struct init? I will know the total amount from the first line of input.

I would be the size that is read in from the use input. Should I just make i a huge number?

struct TaskSet
{
    float priority[i];
    float p[i];
    float w[i];
    float d[i];
};

2 Answers 2

5

You can either use a huge number or use T *arr (together with the size):

struct TaskSet
{
    float *priority;
    int size_priority;
    ...
    float *d;
    int size_d;
};

P.S.: You need to use malloc with the size once read from the user.

Sign up to request clarification or add additional context in comments.

5 Comments

The solution here is MUCH better than using a huge number for i for several reasons. First, you can never be sure that i is "huge enough", and second, nearly all of the time you would be wasting "huge" amounts of space. Dynamic allocation, as outlined here, is exactly the correct solution.
Thanks for the tip. I've never actually used malloc before. So in my main program, i would have something like Taskset.priority = (int*) malloc (i), where i is the number i'm reading from the file? How would i navigate that? just like an array?
@user3287789 You should use Taskset.priority = (float*) malloc (i * sizeof(float)). And navigate it just like normal arrays.
thanks again! first time i've ever done that. I'm not sure what you guys get out of this, but this site is incredibly helpful. Really appreciate the input/help.
@user3287789 This site is fabulous! :P
0

A struct needs to be a known size at compile-time so that the compiler knows how much space to give each one in memory. Consider the following struct:

struct pair{
    int a;
    int b;
};

When you create a struct as a function variable, the compiler creates enough space for two ints on the stack. If you create an array of five structs (see below) the compiler creates enough space for 2*5=10 contiguous ints on the stack:

struct pair p[5];

It is not possible for the compiler to create a struct on the stack if it does not know the size of the struct ahead of time.

Pointers are always the same size, so I recommend using a struct of pointers, like in herohuyongtao's sample code.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.