3

Given this code:

void group::build(int size, std::string *ips){
/*Build the LL after receiving the 
member list from bootstrap*/
head = new member("head");
member *temp1,*temp2;

temp1 = new member(ips[0].data());  // error here
    // ....
}

member::member(char *ip){
strcpy_s(this->ip_addr,sizeof(ip),ip);
this->next = NULL;
this->previous = NULL;
}

And a pointer to string defined as:

std::string *ips;

I want to initialize the array, ips with strings but when I try to get the char data from any array member I get the error:

cannot convert parameter from const char * to char *

Why?

1
  • The use of strcpy_s is wrong. Firstly, the second parameter is the size of the destination buffer, but you aren't providing that. Secondly, sizeof(ip) is the size of a char* in bytes, nothing to do with the length of the string. Commented Oct 17, 2011 at 9:47

6 Answers 6

4

The function you are calling expects a pointer to a modifiable buffer, char*. You are passing a pointer to a non-modifiable buffer, const char*.

Since your member function does not modify its input you should change its declaration to receive const char*.

member::member(const char *ip)
Sign up to request clarification or add additional context in comments.

Comments

1

Change line

member::member(char *ip)

to

member::member(const char *ip)

and, i'm not sure about your usage of strcpy_s

Comments

1

Well, data() returns a const char*, hence the error. You should change member::member to receive a const char*, as you're copying its value anyway.

Also, note that sizeof(ip) is equal to sizeof(char*), which is just a size of a pointer. You should pass the size of the this->ip_addr buffer instead.

Comments

1

Because member::member is defined to take char * as a parameter, and string.data() is giving a const char * as a value (since it is returning a reference to its own internal memory). You could use const_cast or change member::member method signature.

Comments

1

Change this:

member::member(char *ip)

to this

member::member(const char *ip)

That is, you've to change the parameter type of the constructor.


Alternatively, which is also a better solution, simply make the parameter const std::string &:

member::member(const std::string &)

This approach lets use better interfaces provided by std::string class. These interfaces are much more better than C-string interfaces such as strcpy, strlen, strcat etc.

Comments

1

std::string data has this signature

const char* data() const;

You are trying to call the member c'tor with which expects char * so here is your error.

Change this : member::member(char *ip)

To this : member::member(const char *ip)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.