954,492 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

array question

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".

xfruan
Newbie Poster
12 posts since Mar 2005
Reputation Points: 10
Solved Threads: 0
 

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

Dave Sinkula
long time no c
Team Colleague
5,058 posts since Apr 2004
Reputation Points: 2,780
Solved Threads: 314
 

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

return 0;
}

navyblue
Newbie Poster
6 posts since Oct 2004
Reputation Points: 11
Solved Threads: 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? :-|

xfruan
Newbie Poster
12 posts since Mar 2005
Reputation Points: 10
Solved Threads: 0
 

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.

Narue
Bad Cop
Administrator
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You