There seem to be a few similar questions on here though none of them effectively works (at least using my implementation.) I was hoping I could get some insight on why I'm getting the following error:
invalid conversion from char to char* [-f permissive]
#include <ctime>
#include <iostream>
#include "SLList.h"
using namespace std;
int main() {
SLList *newNode;
char name;
int id;
newNode = new SLList;
for( int a = 0; a < 2; a++ )
{
cout << "Type a name: ";
cin >> name;
cout << endl << "Type an integer id: ";
cin >> id;
newNode->insertFirst(name,id);
}
newNode->print();
}
And my class is as follows:
SLList::SLList()
{
first = NULL;
last = NULL;
count = 0;
}
void SLList::print()
{
cout << "List count: " << count <<endl;
node *temp;
temp = first;
while(temp != NULL)
{
cout <<"Name = " <<temp->name <<endl;
cout <<"ID = " <<temp->id <<endl;
cout <<"======================" <<endl;
temp = temp->next;
}
}
void SLList::insertFirst(char *name, int id)
{
node *newNode;
newNode = new node;
assert (newNode != NULL);
newNode->name = name;
newNode->id = id;
newNode->next = first;
first = newNode;
if(last == NULL)
last = newNode;
count++;
}
When I run the main code using name& under insertFirst(&name,id);
The code runs (not as expected) but it at least compiles though name ends up being the same for each. I am fairly new to pointers but was hoping for a little help.
Thanks.
This line: newNode->name = name; is the problem.
I'm guessing what you probably want is not actually a single character, but a string for the name. In that case what you would do is replace that line with:
(don't forget to do #include cstring)
Now, make sure you go look at the strcpy documentation and understand the two arguments that it takes and what it returns. Make sure that you pass strcpy only null terminated c-strings.
This is okay:
This is not okay:
You may get a warning that strcpy is deprecated, you can see about that warning here. But I am guessing that this is for school, so you can probably safely put off such security issues because a hacker probably doesn't care about your homework assignment. Deprecated just means that a newer version of this function has come out and it is not recommended to use it anymore.
Now, let's talk about the error message you got: invalid conversion from char to char*
If instead of copying a whole string, if you really did want just a char, you could do:
or
the -> is an operator that dereferences the pointer given to it. You can also dereference a pointer like this: *name.
doing this: newNode->name is the same thing as doing: newNode.*name