in my program, in insert function:

    void apple :: insert(string s, int a)
    {
         node *ptr;
         ptr = new node;
         strcpy(ptr->name, s);
         ptr->price = a;
         ptr->next=head;
         head=ptr;

    }

this is acctually i want to do

strcpy(ptr->name, s);

but error is:
cannot convert std::string {aka std::basic_string<char>} to char* for argument 1 to char * strcpy(char*, constant char)

any one plz help debug it, fastly, i have very short time to submit my project :(

thank you.

strcpy(ptr->name, s);

strcpy(ptr->name, s.c_str());

However, be very careful that the length of s doesn't exceed the bounds of ptr->name. The ideal (aside from using std::string for name in the first place) is to make name a pointer and allocate memory appropriately:

node *ptr = new node;

ptr->name = new char[s.size() + 1];
strcpy(ptr->name, s.c_Str());

Also don't forget to release your memory. This can all be handled in your node definition through constructors and destructors:

struct node {
    char *name;
    int price;
    node *next;

    node(const std::string& name, int price, node *next = 0)
    {
        this.name = new char[name.size() + 1];
        strcpy(this.name, name.c_str());

        this.price = price;
        this.next = next;
    }

    ~node()
    {
        delete[] name;
    }
};

Then the code becomes as simple as:

void apple::insert(string s, int a)
{
    head = new node(s, a, head);
}
This article has been dead for over six months. Start a new discussion instead.