Click here to Skip to main content
15,918,742 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
Hi,

I have a function that returns an integer. I store that value in a variable "count"

I want to define a new char array whose size is this return value.
e.g. char new_array[count][20]

The column width 20 is constant. This represents the max string length.

But when I do this and try to compile the program it gives me the error:

error C2057: expected constant expression


How can I do this?
Posted
Updated 2-Feb-10 9:33am
v4

Hi,

you can't declare an array with a variable value, because the compiler has to know the array size at compilation time.

What you have to do is to use a pointer to create a dynamic array like this:
main()
{
   int count = 0;
   int *DynArray = NULL;

   count = GetArraySizeFunction();
   DynArray = new int[count];
   if( NULL != DynArray)
   {
      for( int i0 = 0; count > i0; ++i0)
      {
         DynArray[i0] = 0;
      }

      // do with the array whatever you want

      delete[] DynArray; //Rajesh: Replaced delete with delete[]
                         //Carlo: Replaced 'Replacedd' with 'Replaced'  :-\
                         //Armin: Replaced 'Replacced' with 'Replacedd' in Carlos comment ;-)
   }
}
 
Share this answer
 
v6
If you're using C++, then you'd be far better using something like std::vector<int>.

Vectors, lists, queues, etc., provide both good performance and reliability, and they're easy to use!
 
Share this answer
 
v3
The only way to do this is with pointers.

int * myArray = new int[count];

My syntax may be off, I've not done C++ for years, but the core concept is definitely right - the only way to create a dynamic array is with pointers. Your other option is to use dynamic containers like std::vector.
 
Share this answer
 
You need to dynamically allocate memory for your array, for instance:
  int getSize(){ return 3;}

  typedef int Chunk[20];

  void main()
  {
    int i,j, size;   
    Chunk *p;

    size = getSize();
    p = new Chunk[size];
    for (i=0; i<size; i++)
    {
      for (j=0; j<20; j++)
      {
        p[i][j]=i*j;
      }
    }
    delete []p;
}

:)
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900