• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 193
  • Last Modified:

dynamic arrays - store results

Hi,

Can anyone help me how to store results in dynamic arrays, I mean I am not willing to fix array size. I have to store many values in array. For example, lets say I am storing 100 client names and other time I can store 10000 names so it should be dynamic, I cannot fix size.

I need help for how to create it, use it/ call .

Please advise and help.

Thanks
0
Johny12345
Asked:
Johny12345
1 Solution
 
Kent OlsenData Warehouse Architect / DBACommented:
Hi Johny,

If you're going to keep an array of strings, I suggest that you just keep an array of pointers to strings.  It codes a bit easier and can take up less memory.

Object oriented programming makes this a bit easier as it encapsulates all of the controls into one place.  You can do it in C, but if you want to manage multiple dynamic arrays, you probably want to do that with a control structure.  Let's assume just 1 array for now.

//  Define the basic variables.

  char **StringArray = NULL;
  int  StringArrayLength = 0;
  int  StringArrayPosition = 0;

//  Use a function to add items.  (It's just cleaner this way.)

char *AddName (char *Name)
{
  char *N;
  if (StringArrayPosition == StringArrayLength)  // no room to add an item
  {
    StringArrayLength +=50;  // Add 50 pointers every time that it grows
    StringArray = (char**) realloc (StringArray, StringArrayLength * sizeof (char*));
  }
  N = strdup (Name);
  StringArray[StringArrayPosition++] = N;
  return (N);
}

Open in new window


There are a lot of competing theories concerning how to grow that array.  Growing by 1 keeps the array the smallest, but the overhead is significant as you copy and grow the array with every add.  Purists will create it with a default length, then double the size every time it grows.  All are effective so it's just personal preference.

Anyway, that should get you started.


Good Luck!
Kent
0
 
Johny12345Author Commented:
Thanks
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now