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.
A C string is a nul-terminated character array.
The C language does not allow assigning the contents of an array to another
array. As noted by Barry, you must copy the individual characters one by one
from the source array to the destination array. e.g. -
#define _CRT_SECURE_NO_WARNINGS
#include
#include
int main()
{
char str1[] = "Hello";
char str2[10] = {0};
for (int x = 0; x < strlen(str1); ++x)
{
str2[x] = str1[x];
}
printf("%s\n", str2);
return 0;
}
To make this common task easier there are standard library functions provided
which will perform this operation. e.g. - memcpy(), etc.
memcpy(str2, str1, 6);
When the array contains a nul-terminated string of characters you can use
strcpy(), etc.
strcpy(str2, str1);
Caveat: Some of the above functions are considered unsafe as they do not guard
against buffer overruns of the source and destination arrays. There are safer
versions provided by the compiler.
Note that if and when you start learning C++ you will find that there you can
assign a C++ std::string object to another object of the same type. However,
even in C++ the same rules apply when working with C strings, "raw" character
arrays, etc.
- Wayne
str2 is an array. It cannot appear on the left side of an assignment. You will need to use something like strcpy.
q is a pointer. It is perfectly legal to copy one pointer to another.