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 cannot make a variable constant at runtime.
You can change the value of a constant variable
but this won't help. Look at this mini program:


main()
{
const c = 1, *p = &c;

int * q = const_cast<int *>(p);
*q = 10;

char a[c] = {0}; // q == 10 but sizeof a == 1

return 0;
}


When the array is defined, the value of c is 10,
but the size of the array is one anyway.

To create a dynamic array you have to use the new
operator:


main()
{
int n = 10;

char * a = new char[n]; // create array

a[0] = 1;
a[1] = 2; // ...

delete[] a; // free memory

return 0;
}

Hope this helps.

-- ralf
 
sorry I haven't express my problem correct...
I just want to use the variables value to declare the size of the array.

main(){
......
d //my integer variable that I have calculated before.
float A[d][d];
......
}
thanks a lot ralf anyway...
 
> sorry I haven't express my problem correct...

You have, but I think I haven't express my answer
correct. ;-)

> I just want to use the variables value to declare
> the size of the array.

I understand, but you cannot do this. The compiler
has to know the exact size of the array _before_
the program is executed because the memory for
a static array is reserved when the program is
loaded. And the only way to do this is to use a
constant value.

If you do not know the exact size of your array
you may use the operator &quot;new&quot;.
Another 'workaround' is to define an array with
a maximum size, calculate and save its exact size
somewhere and use it as an upper bound in your
iterations.

-- ralf
 
thanks a lot ralf, I'll try it...
 
I did it... thanks ralf again...
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top