Ç - 这是为什么的strcpy()必要 [英] C - why is strcpy() necessary
问题描述
有人能向我解释为什么的strcpy()时,需要分配字符串的字符数组,如下面的code片段。
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;
}
那是什么 S =ABC
失败的原因吗?以及为什么是的strcpy(),他们已被宣布后,指派字符串字符数组的唯一途径?我觉得奇怪,我说,你必须使用一个函数来进行一个基本的任务。
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.
推荐答案
在C数组是不可转让及非复制initializable。这只是阵列如何在C.历史上,在价值方面(关于转让的RHS)阵列衰变为指针,这是正式prevents分配和拷贝初始化。这适用于所有的阵列,不仅字符
数组。
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语言继承了predecessors此数组的行为 - B和BCPL语言。在这些语言中数组被重新利用物理指针psented $ P $。 (很明显的指针重新分配是不是你想要当你分配一个阵列到另一个发生什么。)在C语言中数组不是指针,然而他们由腐烂模拟B和BCPL阵列的历史行为在大多数情况下,指针。这个历史遗留问题是什么让C数组不可复制的这一天。
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";
但仅此而已。
这意味着只要你想复制一个数组,你必须使用一个库级存储复印功能,如的memcpy
。 的strcpy
仅仅是一个专门针对与字符串工作的风味。
This means that whenever you want to copy an 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.
这篇关于Ç - 这是为什么的strcpy()必要的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!