2013-11-20 40 views
2

我想要一個結構中的數組,但我不確定如何去做。我只能在結構中使用一個數組。結構中的數組

typedef struct 
{ 
    int arr[10]; 
} coords; 


coords x; 

printf("Enter X coordinates: "); 

scanf("%d", x.arr[0]); 
scanf("%d", x.arr[1]); 
scanf("%d", x.arr[2]); 
... 

我的問題是我怎麼也輸入數組中的X值?我首先想到了一個二維數組arr[10][10],但它不會工作,因爲我有一些計算要做的X值。

恰當的方法就是定義一個像coords x;這樣的新對象,然後就這麼做了嗎?

基本上我想要結構包含一(1)個數組。我希望結構包含用戶輸入的地圖的x和y座標。在稍後的程序中,我只想用x值進行計算。

+5

我不明白(幾乎)任何東西。你能改說嗎? –

+0

我更新了OP,也許更清晰。 :) – user3005287

+0

你能給我們一個你想使用的數據的例子嗎? –

回答

3

您可以在以下方式使用一對數組的一個結構:

typedef struct 
{ 
    int x[10]; 
    int y[10]; 
} coords; 


coords c; 

printf("Enter a couple of X coordinates: "); 
scanf("%d", &c.x[0]); 
scanf("%d", &c.x[1]); 

printf("Enter a couple of Y coordinates: "); 
scanf("%d", &c.y[0]); 
scanf("%d", &c.y[1]); 

注意,在scanf()你應該通過指針數組元素,而不是元素。

您也可以使用一個 2-d陣列做(X_COOR和Y_COOR可以去掉):

#define X_COOR 0 
#define Y_COOR 1 
typedef struct 
{ 
    int coords[2][10]; 
} coords;  

coords c; 

printf("Enter a couple of X coordinates: "); 
scanf("%d", &c.coords[X_COOR][0]); 
scanf("%d", &c.coords[X_COOR][1]); 

printf("Enter a couple of Y coordinates: "); 
scanf("%d", &c.coords[Y_COOR][0]); 
scanf("%d", &c.coords[Y_COOR][1]); 
+0

但我只能在結構中有一個數組,而不是幾個。 – user3005287

+0

@ user3005287那麼你想如何將它們存儲在一個數組中?交錯? Mean x,y,x,y ... – Michael

+0

@ user3005287一個二維數組在答案中。 – Michael

0

你的代碼是好的,除了你必須把&運營商各scanf的說法之前。

scanf("%d", &x.arr[0]); 

對於Y座標,您應該在結構中定義另一個數組。

0

創建另一個結構數組元素:

typedef struct 
{ 
    int x; 
    int y; 
} coord; 

typedef struct 
{ 
    coord arr[10]; 
} coords; 

用法:

scanf("%d", &x.arr[0].x); 
1

一個更好的解決方法當然是做結構的陣列,因爲你感興趣的事情的核心(座標表示爲一對值)可以很好地模擬爲一個結構:

typedef struct { 
    int x, y; 
} coordinate; 

然後您可以將dec拉上一個陣列很容易:

coordinate my_coords[100];