0

Hi i would like declare a array of size x, this size will be know at runtime (not a static declatrion). how to do that. An efficient way to do that.

I had structure like this

    #define SIZE 50
    struct abc {
                  int students[SIZE];
                  int age;
   }

i would like read SIZE from some point at run time, instead of predefining it.

Edit : can we allocate memory for entire structure including array dynamically.

        strcut abc {
                     int *students; // should point to array of SIZE.
                     int age;
       }s;

can we get sizeof struct = size of entire struct(including array); ?

2 Answers 2

5

If the size is known at runtime, you need to use dynamic allocation.

struct abc 
{
  int *students;
  int age;
}

Then in code,

struct abc var;
var.students = malloc(size*sizeof(int));

and at the end of your code

free(var.students);
Sign up to request clarification or add additional context in comments.

4 Comments

how to handle 2d array, say arry[SIZE] [FIX] ?
second index is predefined, in this can plz provide example. for this use case.
In this case also you need to use a 2D array and malloc it as shown in the above link. Only thing is that FIX will be a constant.
1

There are two maybe simpler solution possible. You can use a empty sized array at the end of the struct:

struct abc {
    int age;
    int students[];
};

unsigned count = 10;
struct abc* foo = malloc(sizeof(*foo) + (count * sizeof(foo->students[0])));

Here you need only one malloc() call if you want both, the struct and the array being allocated dynamically. And also only one free. For a 2d array you have to alloc it as a 1d array and calculate the indices for your own.

An other solution could be:

unsigned count = 10;
struct abcd {
    int age;
    int students[count];
};    

Simple use a variable length array in the struct direct. Here you can use 2d as usual.

1 Comment

Hey thannks, how can we declare a pointer for array inside struct, then allocate memory for enitre struct including array ?

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.