2017-06-05 209 views
1

所以我試圖實現的是從函數返回一個指向二維數組的指針,以便它可以在main()中訪問。我知道有一些C++庫可以幫你實現,比如std::vector,但是我試圖避免動態內存分配,因爲我在嵌入式主板(STM32)上工作,所以我會堅持使用普通的指針和數組。 (也爲一些原因,我不能在KEIL uVision,這也是爲什麼我被迫與指針/陣列工作使用std::array從函數返回指向二維數組的指針 - C++

此外,據我所知,一個指針返回到本地陣列int arr[2][2]定義函數內部不是一個好主意,因爲它在函數返回後將不再有效,這就是爲什麼我創建test_array,在類中聲明並在函數中定義它(作爲全局變量),所以我認爲這應該這不是一個問題。你們有什麼感想?但是,做這種方式提供了一個錯誤「標量初始化多餘元素」

#include <iostream> 
#include "file.hpp" 

int main() { 

    myClass class_object; 

    class_object.value = class_object.foo(); 


} 

//file.hpp 

#include <stdio.h> 

class myClass{ 

    int array[2][2]; 
    int (*foo())[2]; 
    int (*value)[2]; 

    int test_array[2][2]; //declaring here! 

}; 

//file.cpp 

#include "file.hpp" 

int (*myClass::foo())[2]{ 

    test_array[2][2]={ {10,20}, {30, 40} }; //defining here - ERROR!! 

    int arr[2][2]= { 
     {1, 10}, 
     {20, 30} 
    }; 


return arr; 


} 
+2

'int(* myClass :: foo())[2] {'這是一種做功能聲明的新方法,我還沒有涉及到呢?它看起來像gobbledegook!你還在返回你所說的你不知道的地方。最後,告訴我們錯誤發生的地方怎麼樣? – John3136

+3

爲什麼人們如此癡迷C語言數組? :( –

+2

@Baum因爲無能的教授正在教他們這些是重要的,工業可以通過擺脫這些人來節省一大筆錢 –

回答

0

如果你真的想用C-陣列工作,使用的typedef 正常語法:

class myClass{ 
    public: 
    using array2 = int[2][2]; 

    myClass() { 
     test_array[0][0] = 0; 
     test_array[0][1] = 1; 
     test_array[1][0] = 2; 
     test_array[1][1] = 3; 
    } 

    const array2& getArray() const { return test_array; } 
    array2& getArray() { return test_array; } 

private: 
    array2 test_array; 
}; 
+0

我不知道這似乎有點困惑。另外我不想初始化一個數組裏面的數組,但是在函數內部,因爲我在裏面實現了一些數學函數 – Doej

+0

@Doej如果這是嵌入式平臺,並且約束很緊,那麼爲什麼不徹底移除動態內存呢?爲什麼不爲所有可能的結果保留全局內存(假設你知道**該應用程序最多可以產生100個2x2 int數組,所以只需要在編譯時將結果的1600字節內存固定爲全局,並給它的函數目標指針應該做它的計算,而不是返回一些不切實際的指向C數組的指針(它通常很快衰減到普通的'int *',失去了以數組類型開始的任何優點)。 – Ped7g

1

眼前的問題:

test_array[2][2]={ {10,20}, {30, 40} }; //defining here - ERROR!! 

沒有定義。 test_array定義在myClass。這試圖分配給test_array的單個元素,特別是不存在的[2][2]。什麼特別冒犯編譯器不是越界訪問,但={ {10,20}, {30, 40} };試圖將數組填充到單個數組元素中。編譯器期待一個單一的數字,所以四個數字肯定是過剩的。

不幸的是,我不知道你想做什麼的好方法。您可以使用初始化程序列表初始化一個數組,但不能從其中進行分配。

所以

class myClass{ 
public: 

    myClass(); 
    void foo(); 

    int test_array[2][2]; //declaring here! 
}; 

// you can do this: 
myClass::myClass(): test_array{ {10,20}, {30, 40} } 
{ 

} 

void myClass::foo() 
{ 
    // but you can't do this: 
    test_array = { {10,20}, {30, 40} }; 
} 

取決於你做什麼test_array,在構造函數初始化可能會爲你工作。如果你不得不在每次調用數組重置爲foo,也許是一個自動變量是你

void myClass::foo() 
{ 
    int temp_array[2][2] = { {10,20}, {30, 40} }; 

    // use temp_array 

    // maybe copy temp_array to test_array with good ol' memcpy here if you 
    // need to carry the state for some reason. 
} 

更適合沉默的大象在房間裏and gain access to std::array, give this a try.注:我從來沒有這樣做。對我所知的所有人來說,這可能是一場絕對的災難性災難,所以拿一粒鹽來吧。