C++ 将 char* 复制到 char*

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3256454/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 12:27:37  来源:igfitidea点击:

copy char* to char*

c++char

提问by Zee99

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:
Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

AccessViolationException:
试图读取或写入受保护的内存。这通常表明其他内存已损坏。

The problem is due to this:

问题是由于这个:

lKey=p;

How can I assign the lKeyto p?

我怎样才能将 分配lKeyp

回答by Alexander Gessler

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::stringand C string routines for no good reason. Better stick with std::string, it will save you a LOTS of trouble.

您需要预先分配您传递给的内存strcpy。即 ap = new char[s1.length()+1];会这样做(+1 表示终止 0 字符)。但是,std::string无缘无故地混用和 C 字符串例程并不是一个好主意。最好坚持使用std::string,它会为您省去很多麻烦。

Also lKey=pwon't work either -- it just copies the local address of pinto the local variable lKey. The caller won't even see a difference.

lKey=p不会工作——它只是将 的本地地址复制p到本地变量中lKey。来电者甚至看不到任何区别。

回答by James Curran

Actually the problem is strcpy(p,s1.c_str());since pis never set to anything but NULL.

实际上,问题是strcpy(p,s1.c_str());因为p除了 NULL 之外从未设置为任何内容。

回答by Brian R. Bondy

Remember that a char*is just an address of a memory location. You need to have memory allocated at the address.

请记住, achar*只是内存位置的地址。您需要在该地址分配内存。

In your code you don't have memory allocated to use and you didn't set p to point to that memory address.

在您的代码中,您没有分配给使用的内存,也没有将 p 设置为指向该内存地址。

strcpydoes not allocate a buffer, it just takes a memory address to copy the data to.

strcpy不分配缓冲区,只需要一个内存地址来复制数据。

If you are passing a buffer into the function then you probably want simply this (and remove p)

如果您将缓冲区传递给函数,那么您可能只需要这个(并删除 p)

strcpy(lKey, s1.c_str());

回答by jdu.sg

  1. Eliminate p (it is doing nothing here), and copy the data from s1 directly to lkey
  2. Not to beat on you, but the indentation scheme is a travesty, please cop a good style from somewhere ( google 1tbs )
  1. 去掉p(这里什么都不做),直接把s1里面的数据拷贝到lkey
  2. 不要打败你,但缩进方案是一种讽刺,请从某个地方找到一个好的风格(谷歌 1tbs)