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); ?

Vasu
  • 265
  • 1
  • 10
  • 18

2 Answers2

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);
Rishikesh Raje
  • 8,556
  • 2
  • 16
  • 31
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.

kwarnke
  • 1,424
  • 1
  • 15
  • 10
  • Hey thannks, how can we declare a pointer for array inside struct, then allocate memory for enitre struct including array ? – Vasu Mar 21 '16 at 06:31