• C

Dynamic Arrays in C

hi guys

I am using Visual C++ 6... what I want to achieve is a set of arrays that are dynamically created in run time by using a parameter.

For example, if param="A", then my structure would be:

static int myarray1 [SOME_SIZE] = {
FIELD1, FIELD2 };

or
else if param="B", then my structure would be:

static int myarray1 [SOME_OTHER_SIZE] = {
FIELD3, FIELD4, FIELD5, FIELD6 };

what would be the best way to achieve this???
Please give some simple examples...

Thanks !!!

thiamwahAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

lif081199Commented:
int *myarray1 = 0L;
void CreateBuffer(char param)
{
   // kill the old one
   if (myarray1!= 0L) free (myarray1);

   if (param=='A')
      myarray1 = (int *)malloc(SOME_SIZE * sizeof(int));

   else
   if (param=='B')
      myarray1 = (int *)malloc(SOME_OTHER_SIZE * sizeof(int));
}
0
PIGCommented:
If You want not use pointers try that!

static int  myArray[];
....
....
if (param == 'A'){
  myArray = (int*)_alloca(SOME_SIZE*sizeof(int));
}else{
  if (param == 'B')
      myArray = (int*)_alloca(SOME_OTHER_SIZE*sizeof(int));
}
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
lif081199Commented:
Using pointer is better than memory allocation on the stack.

0
PIGCommented:
It is true but question is for static members.
0
SamratAshokCommented:
I think you need little more than above answer
to taclke the problem

struct/union and malloc or new depending upon language
you are using..


definition would be like

union recordStruct
{
  struct ParamA
  {
     ....
     field1 ...;
     field2 ...
  }  
  struct tagParamB
  {
     ....
     field3 ...;
     field4 ...
  }
}

once you have this defined, use malloc/free as other
guys have described earlier

Unless you have reasons to do it in C, I would suggest
using C++ classes and wrap all of this thing neatly
into the class.

0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C

From novice to tech pro — start learning today.