Prerna
Prerna

Reputation: 17

write a function for copying two strings

this code is not printing the copied value of two strings given that are target and source been created above then a function is created that is stringcopy .

#include <stdio.h>

int stringcopy(char *target, char *source) {
    char *start = target;

    while (*target != '\0') { // this means while target is not equal to 0 that is null charecter
        *target = *source;
        target++;
        source++;
    }

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

int main() {
    char source[34] = "Harry";
    char target[34];

    char copy = stringcopy(target, source);
    printf("%s", copy);

    return 0;
}

Upvotes: 0

Views: 86

Answers (1)

Joshua
Joshua

Reputation: 43337

*target != '\0' but *target is uninitialized. You mean *source != '\0'.

Next problem: int stringcopy should be char *stringcopy. Your code will appear to work on a 32 bit platform otherwise, but it will blow up x64. You need to return the correct type.

Third problem: char copy = ; should be char *copy = ; I'm guessing you got here by arbitrarily mutating the code to get it to compile due to the second problem.

Forth problem: return *start; should be return start;. Thanks to Gerhardh for catching it.

Upvotes: 3

Related Questions