Put the code you need help with here.
class vect
{
int nelem; // nombre d'éléments
int *adr; // pointeur sur ces éléments
public:
vect( int n ) // constructeur
{
adr = newint [ nelem - n ];
for( int i = 0; i < nelem; i++ )
adr[ i ] = 0;
std::cout << "++obj taille " << nelem << " en " << this
<< " - v. dyn en " << adr << "\n";
} // fin du constructeur
}; // fin de la classe vect
int main()
{
vect a( 1 );
std::cout << "*** fin main *** " << std::endl;
return 0;
}
error message folows :
terminate called after throwing an instance of 'std::bad_array_new_length'
what(): std::bad_array_new_length
abandon (core dumped)
Actually, original code declares vect a );
and the real fun begins : this noob is stumped and the machine freezes !
Michel Chassey
#include <iostream>
class vect
{
int nelem; // nombre d'éléments
int *adr; // pointeur sur ces éléments
public:
vect( int n, int m ) // constructeur
{
nelem = m;
adr = newint [ nelem - n ];
for( int i = 0; i < nelem; i++ )
adr[ i ] = 0;
std::cout << "++obj taille " << nelem << " en " << this
<< " - v. dyn en " << adr << "\n";
} // fin du constructeur
~vect() {
delete[] adr;
}
}; // fin de la classe vect
int main()
{
vect a( 1 , 3 );
std::cout << "*** fin main *** " << std::endl;
return 0;
}
As "helios" and "Manga" have said "nelem" is never given a value. On my computer an "int' variable that is defined and not given a value usually has the value of "-858993460" known as a garbage value. Which is whatever is at that memory location when the variable is given space at compile time.
Your error message is most likely based on the fact that you are trying to use the "new" to create an array with a negative size. This must be a positive number.
"Manga" has the simplest way of fixing your problem and I would just use it. There is another option, but it is more involved.
Another point you might find a problem with is adr = newint [ nelem - n ];. Subtracting "n" could make your array smaller than you need or even give it a negative value which would cause your error. Yo may find it better to use [nelem + 1] to make it work.
Suggestion/hint a few blank lines would make your code easier to read as in:
class vect
{
int nelem; // nombre d'éléments
int *adr; // pointeur sur ces éléments
public:
vect(int n) // constructeur
{
adr = newint[nelem - n];
for (int i = 0; i < nelem; i++)
adr[i] = 0;
std::cout << "++obj taille " << nelem << " en " << this
<< " - v. dyn en " << adr << "\n";
} // fin du constructeur
}; // fin de la classe vect
int main()
{
vect a(1);
std::cout << "*** fin main *** " << std::endl;
return 0;
}
Also notice the {}s of the blocks. This is how my IDE deals with them, but as you can see it is cleaner. It also make finding the opening and closing braces easier when they line up.