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;
}
CodePudding user response:
*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.
CodePudding user response:
It wasn't me, but someone has written such a function, years ago: strdup
CodePudding user response:
Please see the comments below
#include <stdio.h>
void stringcopy(char *target, char *source) { // nothing need to be returned
// What is the point of this ? 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 not required? Could even delete this line
}
int main() {
char source[34] = "Harry";
char target[34];
stringcopy(target, source); // Do not need to return anything
printf("%s", target); // No need for copy
return 0;
}