cimplicit-declaration

Own implementation of "strcpy" (C) doesn’t work! Conflicting types. Why?


My university advised me to learn C as a Java-programmer from this document: “C for Java Programmers” by J. Maassen.

On page 46 (PDF-page 47), Maassen tries to implement his own version of C’s strcpy function, called my_strcpy

char *my_strcpy(char *destination, char *source)
{
    char*p = destination;
    while (*source != '\0')
    {
        *p++ = *source++;
    }
    *p = '\0';
    return destination;
}

I’ve tried to write a program with this function.
Take a look at page 45 (PDF-page 46). Here, Maassen has introduced his first version of a strcpy-method. He included stdio.h and copied strA to strB.

So, the following program should work, shouldn’t it?

#include <stdio.h>

char strA[80] = "A string to be used for demonstration purposes";
char strB[80];

int main(void)
{
    my_strcpy(strB, strA);
    puts(strB);
}

char *my_strcpy(char *destination, char *source)
{
    char*p = destination;
    while (*source != '\0')
    {
        *p++ = *source++;
    }
    *p = '\0';
    return destination;
}

Well, actually it doesn’t.
Because every time I’m compiling this program, I get the following errors:

PROGRAM.c:12:7: error: conflicting types for ‘my_strcpy’
 char *my_strcpy(char *destination, char *source)
       ^
PROGRAM.c:8:5: note: previous implicit declaration of ‘my_strcpy’ was here
 mystrcpy(strB, strA);
 ^

Why isn’t this program working? I mean, it should work, shouldn’t it?
I’ve seen a similar implementation of a strcpy function here. And that implementation isn’t working either! I’m getting the same errors!

What’s wrong?


Solution

  • When the compiler sees line 8 of your program, it has no idea what types my_strcpy takes or returns. Either switch the order of main and my_strcpy in the source file or add a prototype of my_strcpy before main.