0

I have to write a replacement for strcpy without using pointers or the function having a return value... How could this be done?!

this is what i have so far but it uses return values.

void str_copy(char destination [], char source []) {
    int i;
    for (i = 0; source[i] != '\0'; ++i)
        destination[i] = source[i];
    destination[i] = '\0';
    return destination;
}
  • without using pointers? Not possible. In your example, `destination` and `source` are adjusted to pointers. – ouah Nov 20 '15 at 00:24
  • In C, arrays decays into pointers. See: http://c-faq.com/aryptr/aryptrparam.html – ViniciusArruda Nov 20 '15 at 04:25
  • If is useful for you, you can use `memcpy(destination, source, strlen(source) * sizeof(char))` – ViniciusArruda Nov 20 '15 at 04:29
  • One might note that `strcpy()` returns a `char *` with the target address. If you want a proper replacement, `void` is probably not the proper return type, while `return destination;` is actually fine. – dhke Nov 20 '15 at 10:07

3 Answers3

4

Just remove the return statement.

The function can look the following way

void str_copy( char destination [], const char source [] ) {
    size_t i = 0;
    while ( destination[i] = source[i] ) i++;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
1

Why do you have to return destination? Since you passed the address of the first element by using the empty brackets, the destination array should be changed without the return.

SteveO
  • 131
  • 4
1

suggest writing the function this way:

void str_copy( char destination [], const char source [] ) 
{
    for(size_t i=0; source[i]; i++ )  destination[i] = source[i];
    destination[i] = '\0';
}
user3629249
  • 16,402
  • 1
  • 16
  • 17