2012-02-07 29 views
1

我想創建一個返回數組的函數(在一個項目中)。我不太確定我該怎麼做。如何從函數中正確返回數組?

int worker::*codebook(UnitType type){ 
    int code[12]; 
    if (type == UnitTypes::center){ 
     int temp[12] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}; 
     code=temp; 
    } 
    return code; 
} 

其中worker是類和unitType枚舉。我在頭文件中定義的功能如下:

int *codebook(UnitType type); 

我的問題是這樣的:

cannot convert from 'int' to 'int Worker::* 

這個任何想法?

+0

可能重複的[C++返回數組從函數](http:// stackoverflow .com/questions/8745260/c-return-array-from-function) – 2012-02-07 16:16:42

回答

5

代碼中的第一個問題是語法。簽名應該是:

int* worker::codebook(UnitType type) 

然後,指派給磁盤陣列:

code=temp; 

這只是不是由語言允許的。

最後,它返回一個指向局部變量:

return code; 

的陣列將不復存在當函數返回時,因此任何試圖使用它從外部將導致不確定的行爲。

現在,回答主要問題,如何從函數中正確返回數組?

一種選擇是使用std::vector

std::vector<int> worker::codebook(UnitType type) { 
    std::vector<int> code(12); // vector with 12 zeros 
    if (type == UnitTypes::center){ 
     code[11] = 1; 
    } 
    return code; 
} 

另一種是使用std::array

std::array<int, 12> worker::codebook(UnitType type) { 
    std::array<int, 12> code = {{}}; 
    if (type == UnitTypes::center){ 
     code[11] = 1; 
    } 
    return code; 
} 
+0

好男人謝謝,我明白了! – 2012-02-07 15:01:57

0

這應該是int* worker::codebook(UnitType type)。該*int,使其成爲一個指針 - intint*)。

但是,你真的不想return code這樣的 - 當函數退出,code將指向垃圾(因爲是堆棧上分配)。

+0

呃......挑剔:'代碼'並不僅僅因爲它被分配到堆棧而指向垃圾。如果是這樣的話,堆棧就沒用了。這是因爲'code'是一個本地分配的數組,當函數返回時它會超出範圍。 – 2012-02-07 14:45:16

+0

@SaniHuttunen這就是爲什麼我說「何時退出」。錯字。 – Borealid 2012-02-07 15:59:58

2

您不能返回本地數組,它將在函數退出時超出範圍。

最好使用實際的數據結構,例如std::vector也許。如果你想使用純粹的C級數組,你必須動態地分配內存,併爲函數添加一個方法來表示數組的長度,也許還需要參數size_t& length

+0

所以我的兩個選擇是要麼使用向量或在函數中定義數組的大小? – 2012-02-07 14:44:10

1

簽名應該是:

int* worker::codebook(UnitType type) 

注意,你遇到不確定的行爲。

int code[12]; 

是一個局部變量,當函數退出時它將被銷燬。你正在返回它。永遠不要這樣做。您應該通過new動態分配陣列。

2

你有錯誤的函數原型:

int worker::*codebook(UnitType type){ 

應該

int* worker::codebook(UnitType type){ 

而且這是不正確的,因爲code被分配在堆棧和破壞,當它超出範圍。

你應該在堆上分配這個code數組。那麼這個函數的身體看起來是這樣的:

int* code = new int[12]; 

if (type == UnitTypes::center){ 

    int temp[12] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}; 
    memcpy(code, temp, 12*sizeof(int)); 
} 
return code; 

但隨後調用者應該調用delete[]當它與這陣完成:

int* array = codebook(type); 
delete[] array; 

醜陋的內存管理與這種解決方案連接。既然你使用的是C++,你應該使用一些對象來簡化它(例如std::vector)。

希望這會有所幫助。

0

您的指針聲明位於錯誤的地方。

int* worker::codebook(UnitType type) 

然而,予以警告,要創建您在棧上數組,將得到當摧毀了你的函數退出。您需要在new的堆上創建它,並在完成時記住delete

0

你不想這樣做,因爲這裏的數組內存是在函數內部分配的,並且在函數完成時會消失。將函數的內存/數組分配給另一個參數,並將該數組作爲指針傳入。

0

可以埋葬一個結構裏面的數組,然後通過返回值的結構 - 在經典的C風格:

struct my_array 
{ 
int code[12]; 
}; 

my_array worker::codebook(UnitType type){ 
    my_array arr = {{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}; 
    if (type == UnitTypes::center){ 
     arr.code[11] = 1; 
    } 
    return arr; 
}