2011-11-18 40 views
0

我知道這是很容易的,我期待過的東西,但是這是我有...:快速new運算符的問題

typedef struct 
{ 
    char s1[81]; 
    char s2[81]; 
    char s3[81]; 
}Rec; 

int main() 
{ 

    Rec *a[10]; 

    a[0] = (Rec*)new unsigned char(sizeof(Rec)); 
    a[0]->s1= "hello"; 
    printf("a[0] = %s\n",a[0]->s1); 
    delete(a[0]); 


    getchar(); 
    return 0; 
} 

現在,線

一個[0 ] - > s1 =「hello」;

抱怨表達式必須是可修改的左值。我非常確定這是我在新操作員系列中投放它的原因,並且它需要很長的價值或者其他東西,但我不確定代碼如何實現這一點......我知道但是是的。任何幫助將不勝感激

+0

什麼是舊式'typedef struct {...} Rec;'構造? –

+0

@John我發誓,沒有足夠的重點放在C和C++之間的區別。 –

+0

'new'比'malloc'更強大,因此使用它:'a [0] = new Rec();' – AJG85

回答

5

你不能像這樣分配到char數組。要麼使用strcpy,要麼將char數組更改爲std::string

strcpy(a[0]->s1, "hello"); 

你爲什麼這樣做:

a[0] = (Rec*)new unsigned char(sizeof(Rec)); 

,而不是這樣的:

a[0] = new Rec; 
+1

我的猜測是他做了很多C,並且簡單地用'new unsigned'替換了'malloc' char'。 –

+0

艾蒂安是對的 – Questioneer

0

問題不在於你的鑄造。您的新表達式會分配一個unsigned char並將其初始化爲sizeof(Rec),而不是像new unsigned char[sizeof(Rec)];那樣分配足夠的空間。也就是說,s1"hello"的類型是不同的,你不能指定一個與另一個。您應該使用類似strcpy的東西,但是由於您標記了這個C++那麼您最好使用std::string。另外,你爲什麼不直接致電new Rec;

0

a [0]是指向無法修改的字符數組的指針 - [0]將始終指向相同的地址。 你需要使用strcpy從你的「你好」字符串複製到[0]

+0

'a [0]'是一個指向Rec的指針。如果你的意思是'a [0] - > s1',那不是一個指向數組的指針,它*就是一個數組。 –

3

兩件事。該生產線

a[0] = (Rec*)new unsigned char(sizeof(Rec)); 

分配是被初始化爲sizeof(Rec)unsigned char。你可能意味着

a[0] = (Rec*)new unsigned char[sizeof(Rec)]; 

或更好,但

a[0] = new Rec; 

其次,你不能指定一個字符串到字符數組,你需要一個接一個,例如到字符複製

char s[80]; 
s = "hello"; // won't work 
strcpy(s, "hello"); // correct 

但是,在這種情況下,您應該使用std::string

1

我想你已經在你的生活中做過很多C了。請記住,C++是不同的語言,它恰好與C的大部分語法和它的一些標準庫共享。這意味着C中完美的東西在C++中可能相當醜陋(甚至是危險的)。

隨着中說,讓我們重寫代碼更「C++ - 雜交」的方式:

#include <iostream> // std::cout, std::endl 
#include <string> // std::string 

struct Rec // typedef is implicit for structs in C++ 
{ 
    std::string s1; // use std::string instead of char arrays 
    std::string s2; 
    std::string s3; 
}; // don't forget the semicolon! 

int main() 
{ 

    Rec * a[10]; 

    a[0] = new Rec; // allocates the right amount of memory, no need to cast 
    a[0]->s1 = "hello"; // std::sring handles the assignment for you 
    std::cout << "a[0] = " << a[0]->s1 << std::endl; // use iostreams 
    delete a[0]; // delete is an operator, not a function, no need for parentheses 

    getchar(); // warning, this is not portable 
    return 0; 
} 

正如你看到的,new是不是「改善malloc」。它是類型安全的(不需要強制轉換),使用更安全(它分配所需的確切內存量,不需要sizeof),它也做一些malloc不能做的事情:它調用類的構造函數(就像delete調用析構函數)。

在C++中,如在C中,分配不同於初始化。而在C中你可以只將memset的塊歸零,在C++中對象構造可能會更復雜一點。因此,你應該從來沒有使用malloc來創建具有不平凡的構造函數的類的對象(或有沒有不平凡的構造函數的字段 - Rec就是這種情況)。因爲new總能正常工作,並具有其他功能,所以無論如何您都應該使用它。

+0

也許'std :: cin.get()'而不是'getchar();'...... – AJG85