-1

I know these are just simple programs that copy strings, but I just can't tell why one gives me two warnings, and the other doesn't.

the following code results in a:

warning: comparison between pointer and integer
     while(*source != "\0")
                   ^~

and a:

warning: assignment to 'char' from 'char *' makes integer from pointer without a cast [-Wint-conversion]
     *destination = "\0";
#include <stdio.h>

char* mycopy(char* desitination, char* source);

int main()
{
    char characters[100];
    char replacement[] = "this is replacement text!";
    mycopy(characters, replacement);
    printf("the characters are: %s", characters);
    return 0;
}


char* mycopy(char* destination, char* source)
{
    char* start = destination;

    while(*source != "\0")
    {
        *destination = *source;
        destination++;
        source++;
    }

    *destination = "\0";
    return start;   
}

and the next bit of code works just fine and outputs:

the characters are: this is replacement text!
#include <stdio.h>

char *mycopy(char *destination, char *source);

int main()
{
    char characters[100];
    char replacement[] = "this is replacement text!";
    mycopy(characters, replacement);
    printf("the characters are: %s", characters);
    return 0;
}

char *mycopy(char *destination, char *source)
{
    char *start = destination;

    while(*source != '\0')
    {
        *destination = *source;
        destination++;
        source++;
    }

    *destination = '\0';
    return start;
}

I've been looking at these for a good while now and scoured the internet and have no clue as to why these are different. The only difference I've noticed it that one uses '' instead of "" in some bits, and that same one also has the "*" closer to the identifier than the keywords, but I really didn't think that made any difference.

wojiee
  • 1
  • 2

1 Answers1

1

In C '\0' means character but "\0" means a string.

so when you do *destination = '\0'; you are assigning char 0 to the destination location but when you do *destination = "\0"; you are assigning a pointer pointing to "\0" string to *destination.

balu
  • 1,023
  • 12
  • 18