2013-04-14 59 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)。 這就是我猜的原因。

而這段代碼從構造函數中產生內存泄漏。在這種代碼狀態下,構造函數是不需要的。