Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
281 views
in Technique[技术] by (71.8m points)

string - C - why is strcpy() necessary

Can someone please explain to me why strcpy() is necessary to assign strings to character arrays, such as in the following code snippet.

int main(void) {

char s[4];

s = "abc"; //Fails
strcpy(s, "abc"); //Succeeds

return 0;
}

What is the reason that s = "abc" fails? And why is strcpy() the only way to assign strings to char arrays after they have been declared? It seems strange to me that you have to use a function to carry out a basic assignment.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Arrays in C are non-assignable and non-copy-initializable. That's just how arrays are in C. Historically, in value context (on the RHS of assignment) arrays decay to pointers, which is what formally prevents assignment and copy-initialization. This applies to all arrays, not only to char arrays.

C language inherits this arrays behavior from its predecessors - B and BCPL languages. In those languages arrays were represented by physical pointers. (And obviously re-assignment of pointers is not what you'd want to happen when you assign one array to another.) In C language arrays are not pointers, yet they do "simulate" the historical behavior of B and BCPL arrays by decaying to pointers in most cases. This historical legacy is what keeps C arrays non-copyable to this day.

One exception from the above is the initialization with a string literal. I.e. you can do

char c[] = "abc";

in which case conceptually we are copying string literal "abc" to array c. Another exception is array wrapped into a struct type, which is copied when the whole struct object is copied. And that's about it.

This means that whenever you want to copy a naked (non-wrapped) array, you have to use a library-level memory copying function, like memcpy. strcpy is just a flavor of that specifically tailored to work with strings.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...