Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

use a variable for array index

Status
Not open for further replies.

tgel76

Programmer
Jul 2, 2001
17
0
0
GB
Hi,

How can I use a variable that I have calculated previous in my program as an array index? I mean how can i make it constant? Could you give me an example?

Thanks in advanse...
 
You can't make a variable a constant - you don't have to anyway. Here's how you may use it as an array size:

Code:
main()
{
// ...
// code
// ...
int array_size;
//code that calculates array_size
int *array_ptr = new int[array_size] // for an int array
if (array_ptr == NULL)
    exit(1); // not enough memory
// ...
// ... array_ptr[0] is the 1st element
// ... array_ptr[1] is the 2nd element
// ...
// ... array_ptr[array_size - 1] is the last element
// ...
delete [array_size] array_ptr;
return 0;
}

In case of multi-dimensional arrays only the 1st dimension may be a variable whose value is supplied at runtime. All others must be constant. Example :
Code:
char *array_ptr = new char[array_size][5][10] // for a char array

Hope this helps.

Do correct me if I'm wrong. :)

Ankan.
 
You are right Ankan,
thanks a lot...
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top