You are here:

C++/problem with strcmp function


Hello Zlatko.
I was trying to compare two strings, both char [50] types, using strcmp function. But an error crept in when i tried to compare these strings, one of which is declared in a class and the other in the main function.
I used a member function to return a pointer to the string in class. The exact function and strcmp prototype is given below:

class Person {
     char clsname[50];
     int age;
     char *ptr;
         void getdata(void);
         void display(void);
         char* sendname(void);

char* Person::sendname() {
    ptr = clsname;
    return *ptr;     /*error message -> cannot convert
         from char to char*          */

//In main function,
int main() {
    Person p;
    char name[50] = "some user input";
    if((strcmp(name,p.sendname())) {
        //MORE CODES

Please help me.
And thanks in advance.


Hi Jade

There are two issues.

In the sendname method,
char* Person::sendname() {
   ptr = clsname;
   return *ptr;     /*error message -> cannot convert
         from char to char*          */

you should return ptr, not *ptr. The ptr is a pointer. The *ptr is what the pointer points to which is a character.

The other problem is that clsname is never initialized in your program. You should have a constructor in your Person class which sets clsname to something. Perhaps have 2 constructors like this:

  clsname[0] = 0; // By default set the clsname to be an empty string

Person::Person(char* name)
   strncpy(clsname, name, sizeof(clsname)); // prevent overflow of clsname
   clsname[sizeof(clsname)-1] = 0; // ensure that clsname is terminated.

Use strncpy (instead of strcpy) to prevent copying in more characters than can be held. Unfortunately, strncpy does not put in the final zero byte if there is no space for it. So, you must do it in a separate step.

Since you are using C++, you should avoid using arrays of characters. You should use the string class instead. Try to learn about the string class.

Best regards


All Answers

Answers by Expert:

Ask Experts




No longer taking questions.


No longer taking questions.

No longer taking questions.

©2016 All rights reserved.