2

I have an array inside a structure as below

struct st
{
    ....

    int index[1];

    ....
}

How can I increase size of the array present inside structure to say 6, when I want to use the array inside a function.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294

3 Answers3

2

Probably you looking for struct hack. Struct hack is a technique which allows you allocate additional memory for an array inside struct. Here is an example

struct str {
    int value;
    char ar[0];
};


int main()
{

   struct str *s = malloc( sizeof(struct str) + 20 );
   strncpy( s->ar,"abcd", 5);
   printf("%s",s->ar);
   return 0;
 }

As array defined at the end of the struct, s->ar will get those additional 20 bytes added to sizeof(struct str) in malloc.

Edit as Daan Timmer noted, this technique can be applied only to last member of a struct.

Community
  • 1
  • 1
Dabo
  • 2,371
  • 2
  • 18
  • 26
1

You may try this:

struct st { ....

int index[6];

....
}

Also you may check function malloc() and realloc() in C

On a side note:

You may check STL container like std::vector which encapsulate the associated memory management.

Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
1

An array defined that way exists on the stack. In order to dynamically change the size you will need to use allocate on the heap using malloc realloc and free.

ioseph
  • 1,887
  • 20
  • 25
  • 3
    What do you mean by "exists on the stack" ? Structures and fixed length array can live on the heap too ! – Nicolas Repiquet Apr 29 '14 at 07:27
  • Some further reading I found out globals such as OP's can live on either, or somewhere else, implementation specific. Thanks for the clarification! – ioseph Apr 30 '14 at 02:51
  • You can also allocate a fixed length array on the heap : int (*my_array)[10] = malloc(sizeof *my_array); – Nicolas Repiquet Apr 30 '14 at 14:59