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;


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.

3 Years
Discussion Span
Last Post by deceptikon

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;

        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.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.