You are merely copying the starting address of str to temp. This means that any changes to temp will be reflected in str as well, since they point to the same memory. It does not truly emulate strcpy(dest, src), which creates a separate copy of the null-terminated string pointed to by src starting at the memory location pointed to by dest.
So, to answer your question as asked: no.
If your intent is to avoid the O(n) running time of strcpy, that's also something you can't really do.
If you're required by a programming assignment or exercise to create code functionally equivalent to strcpy, here is a high-level description of the algorithm it uses:
- Copy the character in
*sourceto*destination - If the character that was just copied was the null terminator, exit.
- Otherwise, increment the pointer to
source, and increment the pointer todestination. - Go to step 1.
C strings need to be null terminated. Ie they need a '\0' character at the end, so common string expressions can tell where the string ends. String functions like strcpy and printf("%s... look for this null termination in their operation. When you do this:
for(i=0; s1[i] != '\0'; i++)
s2[i] = s1[i];
You fail to copy the null terminator. This means when you print the string, printf will go through the string until it finds the first '\0' character somewhere after the end of your string. This is why you see the extra characters, and in the case where the NULL is outside your strings allotted memory you will actually cause undefined behaviour by accessing unallocated space, which is very very bad.
You either need to null terminate your string by adding:
s2[i] = '\0'
After your for loop. Or even better, use a standard c function strcpy.
int main()
{
int i, j;
char s1[100], s2[100];
printf("Enter a string : \n");
scanf("%[^\n]%*c", s1);
for(i=0; s1[i] != '\0'; i++)
s2[i] = s1[i];
s2[i] = 0; // null terminate the string
printf("\n the original string is %s\n", s1);
printf("\n the string after copying is %s\n", s2);
return 0;
}
Or simply use strcpy.