将char *复制到char * [英] copy char* to char*
问题描述
这是我的代码的一部分:
Here is part of my code:
extern "C" REGISTRATION_API int extreme(char* lKey)
{
string s1;
char *p=NULL;
try
{
ifstream myfile ("extreme.txt");
int i=0;
if (myfile.is_open())
{
while (getline(myfile,s1))
{
switch (i)
{
case 1:
strcpy(p,s1.c_str());
lKey=p;
break;
//continue here
}
}
}
}
现在,当我从外部应用程序调用此函数时,会收到以下错误:
Now when I call this function from external application, I get this error:
AccessViolationException:
尝试读取或写入受保护的内存。这通常表示其他内存已损坏。
AccessViolationException:
Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
问题是由于以下原因:
lKey=p;
如何将 lKey
code> p ?
How can I assign the lKey
to p
?
推荐答案
您需要预先分配您传递的内存到 strcpy
。也就是说a p = new char [s1.length()+ 1];
将执行它(终止0字符为+1)。但是,混合 std :: string
和C字符串例程并不是一个好主意。更好地使用 std :: string
,它会为你节省很多麻烦。
You need to pre-allocate the memory which you pass to strcpy
. I.e. a p = new char[s1.length()+1];
will do it (+1 for the terminating 0 character). However, it's not a good idea to mix up std::string
and C string routines for no good reason. Better stick with std::string
, it will save you a LOTS of trouble.
也 lKey = p
不会工作 - 它只是将 p
的本地地址复制到本地变量 lKey
。呼叫者甚至不会看到差异。
Also lKey=p
won't work either -- it just copies the local address of p
into the local variable lKey
. The caller won't even see a difference.
这篇关于将char *复制到char *的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!