2012-09-11 56 views
2

的代碼:定義結構陣列中的功能

int i; 
struct st 
{ 
    int m; 
}st_t[2]; 

void foo() 
{ 
    i = 4; 
    st_t[2] = 
    { 
     {10},{20} 
    }; // it's wrong !!!! but I don't know how to do.  
} 
int main() 
{ 
    foo(); 
    cout<<i<<endl;   // will output 4; 
    cout<<st_t[0].m<<endl; // this should output 10 
    cout<<st_t[1].m<<endl; // this should output 20 

    return 0; 
} 

是否有可能定義的功能的結構體數組?如果是,那該怎麼做? 在此先感謝。

PS:
對不起,我的英文不好。我正在製作一個Tetris遊戲,它有一個Shape類,我在Shape.h中聲明瞭一個shape結構數組,然後在Shape.cpp的Shape構造函數中分配給了struct數組。這樣對嗎?或如何分配給結構數組,所以我可以在另一個函數中使用它?

+0

從代碼看來,您似乎想要分配給全局數組,而不是在函數中定義數組。你究竟想要做什麼? –

回答

0

相反的價值觀的直接分配的變量,可以初始化一個臨時變量和該變量複製到您的全局變量:

刪除:

... 
st_t[2] = { 
     {10},{20} 
}; 
... 

,並添加:

... 
st tmp[2] = { {10}, {20} }; 

memcpy(st_t, tmp, sizeof st_t); 
... 

附錄:

如果它不爲你工作,有可能是在你的代碼中的另一個錯誤。從你的例子:

#include <iostream> 
#include <memory.h> 
using namespace std; 

int i; 
struct st { int m; } st_t[2]; 

void foo() 
{ 
i = 4; 
st tmp[2] = { {10}, {20} }; 
memcpy(st_t, tmp, sizeof st_t); // use: const_addr instead of &const_addr 
} 

int main() 
{ 
foo(); 
cout << i << endl;   // will output 4; 
cout << st_t[0].m << endl; // this should output 10 
cout << st_t[1].m << endl; // this should output 20 
return 0; 
} 

所有工作正常,如預期。

+0

它不起作用。主函數的輸出始終爲「0」。 – towry

+0

我爲你嘗試過。輸出是'4,10,20'。看我的附錄。 –

2

你可以初始化一個數組在它定義的地方。即無論是定義移動到功能,或將初始化出來的功能:

struct st 
{ 
    int m; 
} 
st_t[2] = {{10},{20}}; 
0

如果要定義功能的陣列(如你的問題的標題和正文暗示),然後添加類型說明符st的定義:

st st_t[2] = 
{ 
    {10},{20} 
}; 

然而,這將是一個單獨的數組到全局的,所以從main()輸出將不匹配您的評論說什麼應該發生。如果你確實想分配給全局數組,然後:

st_t[0].m = 10; 
st_t[1].m = 20; 

,或者在C++ 11,你可以使用類似的語法來舉例來說,如果你std::array更換普通數組:

std::array<st, 2> st_t; 

void foo() { 
    // Note the extra braces - std::array is an aggregate containing an array 
    st_t = 
    {{ 
     {10},{20} 
    }}; 
} 
+0

感謝您的回答,這對我很有幫助,但沒有解決我的問題。我編輯了我的問題。 – towry

0

如果你只想在功能範圍,然後

void foo() { 
    struct { 
     int m; 
    } st_t = { {10}, {20} }; 
    // do something 
} 
+0

您的示例不會被成功編譯,有更多的初始化程序比成員。 – harper