Gimme dat
Gimme dat

Reputation: 31

Confused on struct array and resizing in C

I'm very confused on a couple of issues.

  1. creating multiple structs of two modifiable variables
  2. increase the amount of structs if needed
  3. store information in the two modifiable variables using pass by value.
  4. Can these values be accessed in constant time?

So lets say I have this..

 void * OPAQUE;

 typedef struct head Head;
 typedef struct data Data;
 struct  head
 {
   int size;
   int capacity;
   Data *info;
 };
 struct data
 {
   int key;
   int values;
 }

passing in values using this function...

 void insert_data(OPAQUE *hOpaque, int key, int data);
 //cast to the known type..

How do I create multiple structures of Data and with each iteration. Each struct gets a new value input so...;

key = 52; data = 43;

those values will be in the first object. Now.. what if I was giving 20 keys and 20 datas. Then I would resize to accommodate the influx of more values to create more structures. I would have 20 structures in total.

Slightly confused on how I should approach this and how it could be done.

Thanks

Upvotes: 1

Views: 2171

Answers (2)

Some programmer dude
Some programmer dude

Reputation: 409166

Just to give you an example, you can do it all manually like

Data *new_data = malloc(old_size + 1 * sizeof *new_data);
if (new_data == NULL)
{
    // Handle error
}
memcpy(new_data, old_data, old_size * sizeof *old_data);
free(old_data);
old_data = new_data;
++old_size;

Or you could do

Data *new_data = realloc(old_data, old_size++ * sizeof *new_data);
if (new_data == NULL)
{
    // Handle error
}
old_data = new_data;

Not counting the error checking and handling, the number of statements have been cut by 60%.

You decide which is simpler. :)

Upvotes: 1

Nunchy
Nunchy

Reputation: 948

You can use malloc() to allocate the structures you need:

Data *info;

Could be used to malloc() a structure(s) of type Data, so if you want to allocate 20 Data structs:

// Inside the function that receives the pointer to Headm assume h
// be the poiner to the Head structure:
h -> info = malloc(sizeof(Data) * 20);

Or dynamically reallocate the structure as needed, if we want to increase to 21 structs, for example:

h -> info = realloc(h -> info, (sizeof(Data) * 21));

Another option might be to do:

 struct  head
 {
   int size;
   int capacity;
   Data info;
 };

 struct data
 {
   int key;
   int values;
 }

 Head **h = malloc(sizeof(Head *) * 20);

To allocate an array 20 Head structures pointer, thus you don't have to malloc() the Data struct. you can then use each Head pointer to allocate individual Head structures:

 int s;
 for (s = 0; s < 20; s++) {
     if ((h[s] = malloc(sizeof(Head))) == NULL) {
         perror("malloc()");
         exit(EXIT_FAILURE);
     }
 }

I suppose there are lot's of ways you can do it, depends on your needs.

Hope this helps.

Upvotes: 1

Related Questions