2013-03-22 28 views
0

我有一個包含string字段的結構。我創建了這些結構的數組,然後我想將它們傳遞給一個函數(通過引用)。當我註釋掉string字段時,一切正常,但如果我沒有程序崩潰。我無法找到一個答案的任何地方..無法在包含字符串的結構數組上運行C++

下面的代碼(我把它降低到只顯示問題):

struct student { 
    int a; 
    int b; 
    string name[20]; 
    char status; 
}; 

void operation(student the_arr[1],int number_of_students) { 
    delete[] the_arr; 
    the_arr = new student[3]; 
    for(int i = 0; i<3; i++) { 
     the_arr[i].a = i+5; 
     the_arr[i].b = i+4; 
    } 
} 

int main() {  
    student *abc; 
    abc = new student[0]; 
    operation(abc, 0); 
    system("pause"); 
    return 0; 
} 

我需要的數組是動態的,這樣我就可以改變它的大小,當我需要。

+6

你應該使用一個向量。 – chris 2013-03-22 16:30:19

+0

是的,使用一個像矢量一樣的C++容器。 – 2013-03-22 16:30:37

+1

'new student [0]','void operation(student the_arr [1],...':WAT? – us2012 2013-03-22 16:31:02

回答

1

假設您不能使用std::vector而不是動態分配的數組,請按照下面的答案。在任何其他情況下,您應該使用標準庫提供的容器。

注意:您的程序不會崩潰。編譯器只會抱怨allocating zero elements部分,但可以讓你編譯和運行這個程序。

你的功能是完全錯誤的。當使用動態分配的,你可以簡單地傳遞這樣的一個指針:

void operation(student* the_arr, int number_of_students) { 

然後你的函數要動態分配內存存儲該the_arr指針,不按引用傳遞中因此導致產生局部的內指針變量執行後,將失去指針:

void operation(student*& the_arr [...] 

我建議你避免下面的解決方案,但並返回新的指針來代替:

student* operation(student* the_arr, int number_of_students) { 
    delete[] the_arr; 
    the_arr = new student[3]; 
    [...] 
    return the_arr; // <---- 
} 

分配abc = new student[0];沒有任何意義。您正試圖分配一個0元素的數組。也許你的意思是abc = new student[1];

+0

雖然存在問題,但它們不應該像現在這樣對發佈的代碼產生影響。儘管存在內存泄漏,但我感覺發布的代碼不會崩潰。 – chris 2013-03-22 16:40:42

+1

@Jueecy:你確定這是無效的嗎? – 2013-03-22 16:46:12

+0

@OliCharlesworth,不,不知道了。 – Shoe 2013-03-22 16:51:01

0

您應該只使用向量或其他序列對象。雖然我不確定你想要用你的代碼做什麼。這裏有一個簡單的例子:

// Vector represent a sequence which can change in size 
vector<Student*> students; 

// Create your student, I just filled in a bunch of crap for the 
// sake of creating an example 
Student * newStudent = new Student; 
newStudent->a = 1; 
newStudent->b = 2; 
newStudent->name = "Guy McWhoever"; 
newStudent->status = 'A'; 

// and I pushed the student onto the vector 
students.push_back(newStudent); 
students.push_back(newStudent); 
students.push_back(newStudent); 
students.push_back(newStudent); 
+0

他說他不能使用載體。可能是因爲這是功課。 – Shoe 2013-03-22 16:42:14

+1

無論如何,使用「學生」矢量,而不是「學生*」的矢量。 – chris 2013-03-22 16:43:36