I wanna create an array whose size would be determined by a variable, but i when i write the following, i got an error

int main ()
{
int a;
std::cin >> a;
int intArray [a];

return 0;
}

the error is "an constant expected".

The error is correct -- you can't do that in todays C++. Have you been introduced to new/delete?

you can't use a variable define a array's size
#include <iostream.h>
int main ()
{
int a;
cin >> a;
int *intArray;
intArray=new int(a);

return 0;
}

Thanks for the answers, i can solve my problem now. But i got another question regarding arrays. I tried to make an array of c-style strings with the following code, but got an error:

int main ()
{
    char ** strArray = new char [5][30];
    //using the array

    delete [] strArray;
    return 0;
}

the error message is: "the compiler is unable to convert from the type char (*) [30] to the type char **."

Why is it so and how can i solve it? :-|

Multidimensional arrays are actually arrays of arrays, so you need to allocate memory to reflect that:

char **p = new char*[rows];

for ( int i = 0; i < rows; i++ )
  p[i] = new char[cols];

Then to free them:

for ( int i = 0; i < rows; i++ )
  delete [] p[i];
delete [] p;

The nice thing is that you can index an array allocated like this with the subscript operator:

cout<< p[i][j] <<endl;

Not all multidimensional allocation schemes allow you to do that.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.