2016-09-17 122 views
-4

我想我在一個函數創建一個結構傳遞給另一個函數所以基本上什麼即時試圖做的是動態創建必要的結構量是一個文本文件,以便在文本文件中會有一個結構的量數字像5和5個數據集。我想將我在函數中創建的結構傳遞給另一個函數。幾個月前我開始編程,所以如果有一個簡單的解決方案或者這個問題已經被問到,請原諒我。結構指針功能?

struct graph 
{ 
int Max,Min,index; 
double dataArray[300]; 
}; 

void readfile() 
{ 
int amount; 
char tmpSTR,nmbrGraph; 
ifstream myFile("data1.txt",ios::in); 
myFile>>amount; 
myFile>>tmpSTR; 
myFile>>nmbrGraph; 
graph* Data = new graph[amount]; 

    for(int j=0;j<nmbrGraph;j++) 
    { 
    for(int i=0;i<299;i++) 
     myFile>>Data[j].dataArray[i]; 
    } 
//hOW WOULD I PASS THE STRUCTURE "DATA" TO THE FUNCTION anotherFunction? 
} 

void anotherFunction() 
{ 
for(int i = 0;i<300;i++) 
cout<<Data[scroll].dataArray[i])<<endl; /*Error here! scroll being an 
integer declared globally*/ 
} 
+0

「...將我在我的函數中創建的結構傳遞給另一個函數」 - *參數*將是必需的,除非您打算使用不明智的棧全局變量。另外,爲了你的目的,我希望在發佈的代碼中'nmbrGraph <= amount'確實如此,否則你已經調用了未定義的行爲。 – WhozCraig

回答

2

傳遞graph*指針由值或參考anotherFunction作爲參數。此外,包含數字項目也很重要,因爲這是通過閱讀文件確定的,並且事先不可知。

// by value 
void anotherFunction(graph* Data, int amount); 
// by reference 
void anotherFunction(graph*& Data, int amount);