Hello, i have a problem with the C++. Below is the code. When compile, there is an error.

error C2466: cannot allocate an array of constant size 0

Can anybody answer me?

#include <iostream.h>
#include <string.h>


class samp{
    int a;
public:
    void set(int n){a=n;}
    int get() {return a;}
};



int main()
{
int x;
cin>>x; 
samp obj[x];

    int i;

        for(i=0;i<x;i++)
        obj[i].set(i);

        for(i=0;i<x;i++)
        cout<<obj[i].get();


        return 0;

}

Edited 3 Years Ago by pyTony: fixed formatting

Guess it is because of this part.

int x;
cin>>x;
samp obj[x];

either define an array of samp like samp obj[ 10 ] or use the new operator like this. samp* obj = new samp(x);

Thank you;

But I want a user input , so I tried your second suggestion.

"samp* obj = new samp(x);"

Below is the error:

C:\Documents and Settings\Administrator\Desktop\oop\Cpp2.cpp(18) : error C2664: '__thiscall samp::samp(const class samp &)' : cannot convert parameter 1 from 'int' to 'const class samp &'
Reason: cannot convert from 'int' to 'const class samp'
No constructor could take the source type, or constructor overload resolution was ambiguous

Thanks a lot wolfpack .

Can you explain to me why "samp obj[x]" is wrong ?
Can you also explain this code to me ?
Samp* obj = new Samp[ x ];

you use

samp obj[SOME_CONSTANT]

for static memory allocation. The storage area is assigned at compile time.
The keywork new in C++ is like malloc in C. You use it to create a memory storage area at runtime. This memory is created in the free store. So you have to call delete for each new statement you use. Since you want x numbers of Samp at runtime and not compile time, you cant use the static array. You must use the dynamic allocation in the form of

Samp* obj = new Samp[ x ]; // Allocate Memory

....
delete [] obj;// Deallocate Memory
This article has been dead for over six months. Start a new discussion instead.