|
From: Bob W. <bo...@ph...> - 2002-04-19 21:57:34
|
David,
An array is not dynamic, the value you pass it at initalization must =
be a constat of some sort.if 'i' were to change during the program some =
weird voodoo (the program will crash,the world will end,etc.) all this =
will hapen because it cannot change the size of an array at =
runtime(reason no. 1 linked lists were created)
I am in the process of learning C++, as Ioannis well knows, and a week =
or so ago I was working on the array chapter. In the past I have done =
most of my programming in pascal, and every pascal compiler I have used =
will not compile an array if the size of the array is a variable, i.e., =
no dynamic arrays. Just fooling around I modified the simple little C++ =
array program to define an array with a variable. I had not done any =
research but was confident that the compiler would flag an error and =
bail out.=20
Not So! the program compiled and ran allowing me to change the size of =
the array. I tested the bounds of the program and could build quite =
large arrays. the size_of function always returnd the correct size of =
the array. I was really surprised because that it worked. I have not =
employed the technique in any real world program, because I felt that it =
would be much safer with pointers and linked lists.=20
Your message above confirmed what I suspected but had not taken the time =
to investigate. Stroustrup says:
The number of elements of the array, the array bound, must be a =
constant expresseion (=A7C.5)
Paragraph C.5 says in part:
A constant expression evaluates to an integral of enumeration =
constant. Such an expression is composed of literals, enumerators, and =
const initialized by constant expressions. < . . . > Intuitively, =
constant expressions are simple expressions that can be evaluated by the =
compiler before the program is linked and starts to run.
That tells me that the compiler should have caught this and bailed out =
rather than compiling, linking, and running this program:=20
#include <iostream.h>
#include <stdlib.h>
int main
{
int arraySize =3D 1;
std::cout << "Enter the size of the array: ";
std::cin >> arraySize;
if (!(arraySize > 0))
{
system("pause");
return 0;
}
int myArray[arraySize];
int arrayLength =3D sizeof(myArray)/sizeof(myArray[0]);
for (int i=3D0; i < arrayLength; i++) // 0 to arrayLength-1
{
myArray[i] =3D (i + 1) * 2 + 1;
}
for (int i=3D0; i< arrayLength; i++) // 0 to arrayLength-1
{
std::cout << i << ": " << myArray[i] << "\n";
}
=20
system("pause");
return 0;
}
The faulty compiler is the one used by Bloodshed. Visual C++ 6.0 caught =
the error. That is the second and most serious problem I have found with =
the compiler used by the dev-c++ environment. It appears it will =
properly compile ANSI standard code, but it will also compile code that =
is clearly outside of the standard.=20
I believe that the dev-c++ compiler is the mingw compiler.=20
Regards,
Bob Wilson
|