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.
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.
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.
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.
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
.