I was trying to do build my program and it kept giving me the following error:
Error C2440: 'return': cannot convert from 'int' to 'elem *'
Problem is that the only way I've found to fix it was to change it to return=0 but that would make the whole thing pointless given that I want it to return 1 when I have successfully removed an element from the queue. Do you have any idea how to fix it?
struct elem { int key;
elem *next;
} *first=NULL, *last=NULL;
elem *push(int n, elem *&first, elem *&last)
{ elem *p=last;
last=new elem;
last->key=n;
last->next=NULL;
if(p!=NULL)
p->next=last;
else
first=last;
}
elem *pop(int &n, elem *&first, elem *&las)
{ elem *p=NULL;
if (first)
{ n=first->key;
p=first;
first=first->next;;
if (first==NULL)
last=first;
delete p;
return 1; //this here gives me the error
}
else
return 0;
}
c++ won't let you convert an integral type to a pointer without reinterpret_cast
or c-style cast
however your function is misleading and you are doing things that should never be done.
char *ptr = 1; // error
char *ptr = reinterpret_cast<char*>(0x164651); // compiles but you must make sure this address will be valid !
You declare your function to return an elem *
and makes this an indication to success or failure, In this case you should return nullptr
on failure and a pointer to the pushed or popped element on success.
elem *pop(int &n, elem *&first, elem *&las)
{ elem *p=NULL;
if (first)
{ n=first->key;
p=first;
first=first->next;;
if (first==NULL)
last=first;
return p; // return the popped element to the caller
}
else
return nullptr; // failed to pop any element
}
If you insist on indicating success and failure by 1 and 0 values so you should use an integral type as the return type no a pointer.
int pop(int &n, elem *&first, elem *&las) // returns 1 on success otherwise 0
and in c++ it's more better to use exceptions to indicate failure. This allows to separate failure path from return path and save a lot of error checking which you will find yourself doing most of the time. So Always use c++ exceptions and RAII if possible, it will save you much.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.