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;
    void set(int n){a=n;}
    int get() {return a;}

int main()
int x;
samp obj[x];

    int i;



        return 0;


Recommended Answers

All 5 Replies

Guess it is because of this part.

int 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

Sorry my mistake.
It should be this.

Samp* obj = new Samp[ x ];

sorry again.

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


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
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.