2013-04-14 58 views
4

我想初始化一个char *字符串,在一个结构中。字符指针的C++错误

这是结构:

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; 

这就是地步chrash ..

void Initialize(MyString& string){ 

    string->data = new char[LENGHT]; 
    string->data[0] ='\0'; // this generate an error! 
    string->addCopyRef(); 
} 

这是主要的:

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

第一个是怎么回事好吧,第二不.. 可以请你帮我理解问题在哪里?谢谢!

+3

名称'__String'是为实现保留的,所以您有未定义的行为。另外'MyString'是一个指针类型。你如何调用函数? –

+1

如何定义“LENGHT”?你的意思是'长度'? – Floris

+1

'MyString'是指针,也许是'NULL'。 – fasked

回答

7

你需要将它们传递这样之前的对象分配内存:

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

作为一般建议不要做这样的typedef,他们都非常混乱,且容易出错。如果你决定键入一个指针,至少要指明它是这种类型的指针,例如:typedef struct __String* MyStringPtr

+0

不,它不是 - MyString是一个指针(!),所以没有构造函数被调用。 –

+0

typdef总之罐GE读为typedef结构__String * MyString',从而MyString的是一个指针,指向__String。 – alexrider

+0

@TomerArazy,是的,我没有看到微小的星号类定义后:/ – chris

2
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] ='\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_string,right_string,both_string)。 这就是我猜的原因。

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