为什么我的源在c中使用strcpy时会发生变化

mal*_*thi 2 c c++ strcpy

使用strcpy源后,损坏并获得正确的目标.以下是我的代码请告诉我为什么我的源代码被破坏了?如果我将第二个字符数组q []保持固定大小,那么我的源码不会被更改.为什么这种奇怪的行为.-
我正在使用MSVC 2005

void function(char* str1,char* str2);
void main()
{

    char p[]="Hello world";
    char q[]="";
    function(p,q);
    cout<<"after function calling..."<<endl;
    cout<<"string1:"<<"\t"<<p<<endl;
    cout<<"string2:"<<"\t"<<q<<endl;
    cin.get();
}

void function(char* str1, char* str2)
{
    strcpy(str2,str1);
}
Run Code Online (Sandbox Code Playgroud)

OUTPUT:

after function calling...
string1:        ld
string2:        Hello world
Run Code Online (Sandbox Code Playgroud)

提前
谢谢马拉蒂

Ben*_*ery 8

strcpy不分配存储字符串所需的内存.在执行str2之前必须分配足够的内存strcpy.否则,在覆盖某些未分配的内存时会出现未定义的行为.


Thi*_*ter 6

q只有1个字符的空格,这是终止\0.请阅读一本关于C的书 - 你需要学习一些关于内存管理的知识.

最有可能你的内存看起来像这样(简化)Qpppppppppppp.因此,当你strcpy q,你将覆盖部分p内存.

由于您使用的是C++:只需使用std::string和/或std::stringstream代替原始char数组.