Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conversion from 'myItem*' to non-scalar type 'myItem' requested

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?

like image 651
kralco626 Avatar asked Oct 12 '10 23:10

kralco626


2 Answers

Try:

MyItem * item = new MyItem;

But do not forget to delete it after usage:

delete item;
like image 63
tibur Avatar answered Nov 19 '22 14:11

tibur


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.

like image 28
Nick Meyer Avatar answered Nov 19 '22 15:11

Nick Meyer