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?

[Webinar] Streamline your web hosting managementRegister Today

x
 
PIGConnect With a Mentor Commented:
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
 
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
 
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
All Courses

From novice to tech pro — start learning today.