字符指针出现C++错误

C++ error on char pointer

本文关键字:C++ 错误 指针 字符      更新时间:2023-10-16

我想初始化结构中的char*字符串。

这是结构:

typedef struct __String  {
    char*    data;        // C-string data, 
    unsigned* copyRef;     // number of copy reference, delete only when the copyRef is 0
    bool     isACopy;     // this boolean is true when *data is a ref to an other MyString
  __String () {
      data = 0;
      isACopy = false;
      copyRef = new unsigned();
      *copyRef = 0;
      return;
 }
    void addCopyRef() {
        *copyRef++;
    }
    void removeCopyRef() {
        *copyRef--;
    }
 } *MyString;

这就是它的特点。。

void Initialize(MyString& string){
    string->data = new char[LENGHT];
    string->data[0] =''; // this generate an error!
    string->addCopyRef();
}

这是主要的:

MyString left_string, right_string, both_string;
Initialize(left_string);
Initialize(right_string);
Initialize(both_string);

第一个进展顺利,第二个进展不顺利。。你能帮我弄清楚问题出在哪里吗?谢谢

在像这样传递对象之前,您需要为对象分配内存:

MyString left_string = new __String();
Initialize(left_string);

一般建议不要做这样的typedef,它们非常令人困惑,而且容易出错。如果您决定对指针进行typedef,则至少表明它是类型中的指针,即:typedef struct __String* MyStringPtr

typedef struct __String  {
  char*    data;        // C-string data,
  unsigned* copyRef;    // number of copy reference,
                        // delete only when the copyRef is 0
  bool     isACopy;     // this boolean is true when *data
                        // is a ref to an other MyString
  __String () {
    data = 0;
    isACopy = false;
    copyRef = new unsigned;
    *copyRef = 0;
    return;
  }
  void addCopyRef() {
    *copyRef++;
  }
  void removeCopyRef() {
    *copyRef--;
  }
} *MyString;

void Initialize(MyString& string){
  string->data = new char[100];
  string->data[0] =''; // this generate an error!
  string->copyRef = new unsigned();
  string->addCopyRef();
}
int main()
{
  MyString mystring = new struct __String;
  Initialize(mystring);
}

我这样测试没有任何错误。在linux上使用g++。我想你最好

  • 至少在此处提供错误消息
  • 以及您所使用的编译器和平台

我用下面的另一个main((再次进行了测试。

int main()
{
  MyString mystring = new struct __String;
  MyString mystring1 = new struct __String;
  MyString mystring2 = new struct __String;
  Initialize(mystring);
  Initialize(mystring1);
  Initialize(mystring2);
}

使用此测试代码,不会出现错误。我认为您错过了实例化由mystring(在您的代码中,left_stringright_stringboth_string(指向的对象。我想这就是为什么。

这段代码会从构造函数中产生内存泄漏。在这种代码状态下,不需要构造函数。