0

In C++ (compiler : clang++), when compiling the following code:

char* strcpy(char * dest, const char * src)
{
    char* result = dest;
    if(('\0' != dest) && ('\0' != src))
    {
        /* Start copy src to dest */
        while ('\0' != *src)
        {
            *dest++ = *src++;
        }
        /* put '\0' termination */
        *dest = '\0';
    }
    return result;

}

I get the following error code:

string/strcpy.cpp:12:11: error: comparison between pointer and integer
      ('int' and 'char *')
        if(('\0' != dest) && ('\0' != src))
            ~~~~ ^  ~~~~
string/strcpy.cpp:12:29: error: comparison between pointer and integer ('int'
      and 'const char *')
        if(('\0' != dest) && ('\0' != src))

I'm aware that most of the errors related with this error are produced when the characters to compare are between quotation marks instead of apostrophes, but in this code this is not the case. Why is this error produced? Thanks in advance!

8
  • What part of the error messages confuses you? Commented Jan 12, 2018 at 19:01
  • 2
    dest is a pointer. *dest is the value of the thing it points to. You compare correctly later with '\0' != *src. Seems like a simple typo to me. Commented Jan 12, 2018 at 19:01
  • 2
    strcpy bad name. Commented Jan 12, 2018 at 19:02
  • @FrançoisAndrieux That fixed the code, thx Commented Jan 12, 2018 at 19:04
  • @manni66 In the freestanding environment that I'm using strcpy is a valid name Commented Jan 12, 2018 at 19:05

2 Answers 2

1

you mean

if((NULL != dest) && (NULL != src))

of even more idiomatic

if((dest) && (src))
Sign up to request clarification or add additional context in comments.

Comments

1
('\0' != dest)

In the above, '\0' is a char literal, but dest is a pointer to a char. This is the reason for the error being thrown.

I believe the problem would be fixed if you change the conditional to

('\0' != *dest)

EDIT: Whoops, I thought you were trying to check if the string is at it's end. If you were trying to check if the pointer is null, the correct way would be to simply evaluate it as conditional.

if(dest)

1 Comment

Oddly enough, although the correction you propose would indeed resolve the type mismatch, I don't think it's the right correction for the context. It doesn't make sense. I think the OP means to perform null-pointer checks there.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.