I have this C++ code:
#include
using namespace std;
struct MyItem
{
int value;
MyItem* nextItem;
};
int main() {
MyItem item = new
Try:
MyItem * item = new MyItem;
But do not forget to delete it after usage:
delete item;
First of all, this code won't compile because you forgot the semi-colons after each member variable declaration and after MyItem
declaration and the keyword "struct" is typed wrong. Your code should look like this:
struct MyItem
{
var value;
MyItem* nextItem;
};
MyItem item = new MyItem;
Now answering your question, this code does not work because the new operator returns a pointer to the object created (a value of type MyItem*
) and you are trying to assign this pointer to a variable of type MyItem
. The compiler does not allow you to do this (because the value and the variable have different types). You should store the pointer into an apropriate variable, like this:
MyItem* item = new MyItem;
In this case, you must remember to delete item
to avoid memory leak once you no more need it.
Alternatively, you can create the object in the stack without the new
operator.
MyItem item;
In this case, the object ceases to exist when the function returns; you don't need to remember to delete it.
Here is edited code with changes mentioned on the right
struct MyItem // corrected spelling struct
{
var value; // added ;
struct MyItem * nextItem; // add "struct" and added ;
}; // added ;
MyItem * item = new MyItem; // added * before item
delete item; // not exactly here, but some where in your code
BTW, you don't have to do new
. You can possible create a MyItem
object on the stack as
MyItem anotherItem;
You've mixed
MyItem item;
which allocates an instance of MyItem
on the stack. The memory for the instance is automatically freed at the end of the enclosing scope
and
MyItem * item = new MyItem;
which allocates an instance of MyItem
on the heap. You would refer to this instance using a pointer and would be required to explicitly free the memory when finished using delete item
.