I have this C++ code:
#include <iostream>
using namespace std;
struct MyItem
{
int value;
MyItem* nextItem;
};
int main() {
MyItem item = new MyItem;
return 0;
}
And I get the error:
error: conversion from `MyItem*' to non-scalar type `MyItem' requested
Compiling with g++. What does that mean? And what's going on here?
Try:
MyItem * item = new MyItem;
But do not forget to delete it after usage:
delete item;
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With