- #1
galaxy_twirl
- 137
- 1
Moved here from non-homework forum, therefore template is missing
Hi everyone. I ran into a problem while trying to code the string function, strcpy, without the use of <string.h>. The function, strcpy, which I have to make myself is exactly the same as the strcpy in <string.h>.The question in my homework is:
Implement the my_strcpy(s1,s2) function that copies string s2 to s1, including the terminating null character, topping after the null character has been copied. String s1 is returned. Use char *my_strcpy(char* s1, const char* s2) as your function and write the main program to test the functionality of your function.
My codes are below:
When I ran the above code, it gave me a segmentation fault. I have a feeling there is something wrong with my printf and my_strcpy function (in terms of how it is called in main) and most prolly, my loop construct, cos a seg. fault probably means my program accessed memory it was not allocated with.
Any help is greatly appreciated! :D
Warmest Regards,
galaxy_twirl
Implement the my_strcpy(s1,s2) function that copies string s2 to s1, including the terminating null character, topping after the null character has been copied. String s1 is returned. Use char *my_strcpy(char* s1, const char* s2) as your function and write the main program to test the functionality of your function.
My codes are below:
Code:
#include <stdio.h>
char *my_strcpy(char* s1, const char* s2);
int main(void)
{
char str1[4]={"Cat"};
char str2[4]={"Dog"};
char* s1;
char* s2;
s1 = &str1[0];
s2 = &str2[0];
my_strcpy(s1, s2);
printf("New string: %s\n", s1);
return 0;
}
char *my_strcpy(char* s1, const char* s2)
{
while(s1 <= s2)
{
*s1 = *s2;
s1++;
s2++;
}
return;
}
When I ran the above code, it gave me a segmentation fault. I have a feeling there is something wrong with my printf and my_strcpy function (in terms of how it is called in main) and most prolly, my loop construct, cos a seg. fault probably means my program accessed memory it was not allocated with.
Any help is greatly appreciated! :D
Warmest Regards,
galaxy_twirl
Last edited: