-2

I am having a structure

typedef struct
{
    UINT32 num_pairs;
    UINT32 value;
}
SCSI_ENTRIES;

I need to dynamically instantiate the objects for this structure on fly .

for (int i = 0; i < 50; i++)
{
    if ( port[i] )
    {
        port_valid_count += 1;

        // Please tell me how to instantiate 
        // SCSI_ENTRIES objects dynamically, 
        // based on port_valid_count.

        // Something like SCSI_ENTRIES entries[port_valid_count] ;
    }
}

I need to increase the objects for the structure every time the port_valid_count is incremented.

user1846251
  • 29
  • 1
  • 5
  • 2
    Just use `realloc()` to allocate a larger array? – Jesus Ramos Oct 22 '14 at 20:15
  • Possible duplicate of [Dynamically increase/decrease array size](http://stackoverflow.com/questions/16689847/dynamically-increase-decrease-array-size). You could also try implementing your own vector in C (e.g. this article: [Implementing a dynamic-vector array in C](http://eddmann.com/posts/implementing-a-dynamic-vector-array-in-c/)). – vgru Oct 22 '14 at 20:20
  • Can someone illustrate me the sample code.I tried realloc(entries , port_valid_count*sizeof(SCSI_ENTRIES)); – user1846251 Oct 22 '14 at 20:32
  • @user1846251: read the answers in the linked thread. One of them has [this link](http://www.cplusplus.com/reference/cstdlib/realloc/) to `realloc`, mentioned by @Jesus above. Or this answer: [How to use realloc in C](http://stackoverflow.com/questions/13748338/how-to-use-realloc-in-a-function-in-c). – vgru Oct 22 '14 at 20:34

1 Answers1

0

There are two ways to do this. One is to have 2 items, a fixed-size struct and a variable-sized block of space that holds the array. A pointer in the struct would point at the variable-sized block; the struct would also hold a count of the number of items in the variable-sized block. The other approach is to have a single variable-sized block of space to hold N array items. I recommend you search for and read about 'variable length array in C' and similar. (This is not a small topic easily answered here.)

Here are starting points: Variable length arrays in struct and variable size struct.

Community
  • 1
  • 1
Art Swri
  • 2,799
  • 3
  • 25
  • 36