【问题标题】:Strcpy does not copy an allocated character arraystrcpy 不复制分配的字符数组
【发布时间】:2012-04-04 14:42:34
【问题描述】:

为什么这不起作用:

SomeClass::SomeClass(char *lit) //Ctor
{
    str = new char[strlen(lit)+1]; // str is a pointer to char in SomeClass
    strcpy(str,"have");
    cout << str << " " << "In Ctor" << " +Size=" << strlen(str)<< endl;
}

上面的代码显示了一个长度为 0 的字符串。但是这段代码有效:

SomeClass::SomeClass(char *lit)
{
    char newstr[strlen(lit)+1];
    strcpy(newstr,"have");
    cout << newstr << " " << "In Ctor" << " +Size=" << strlen(newstr)<< endl;
}

Here是完整的代码。

编辑:
添加了指向 Ideone 的链接,在我回答问题后 OP 删除了该链接。
没有源代码的链接,这个问答是没有用的。

【问题讨论】:

  • 请制作一个完整简短程序来演示您所看到的错误。请参阅sscce.org 了解更多信息。
  • 在这两种情况下,您都将数组的大小调整为传入字符串 lit 的长度。有什么保证lit 至少有四个字符长?
  • @amit:不,C++ 没有 VLA,尽管一些编译器(例如 gcc)将它们作为扩展包含在内。在不相关的说明中,是否有充分的理由经历所有这些回旋而不是仅仅使用std::string
  • 请使用您的复制和粘贴工具发布实际的程序输出和/或错误消息,而不是“不起作用”。
  • 为什么要删除源代码的链接?没有它,Q 和答案对于将来遇到类似问题的任何人都是无用的。请将其编辑回 Q!

标签: c++ arrays string character


【解决方案1】:

strcpy 没有问题,你只是在弄乱你的指针。

问题出在这里:

 str = new char[strlen(lit)+1];
 strcpy(str,lit);
 length=leng();    <------------- str points to \0 after this call
 cout << str << " " << "In Ctor" << " +Size=" << strlen(lit)<< endl;

str 是你的类成员,你在函数leng() 中移动指针str 指向\0,自然,你在下一条语句中看不到任何输出。

解决方案是将起始地址保存在函数内部的单独指针中。

int String :: leng()
{
      int length=0;
      char *tempPtr= str;       <----------- Store the address in a temporary pointer
      while(*str)
      {
                 length++;
                 str++;
      }
      str = tempPtr;            <---------- Point the Pointer member to right address again
      return length;
}

【讨论】:

  • 另外,将String::leng()方法设为const,这样不修改类状态(包括str数据成员)的约束就更明显了。
【解决方案2】:

另一种写法String::leng()

int String::leng()
{
    char *endPtr = str;
    while(*endPtr)
        endPtr++;
    return endPtr - str;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-09
    • 1970-01-01
    • 2020-02-17
    • 2011-07-04
    • 1970-01-01
    • 2013-02-26
    • 2010-11-20
    相关资源
    最近更新 更多