2016-03-08 85 views
0

我很困惑這些C指針如何工作。C指針與Structs和2D數組

這裏是我想要做的事:

創建具有行,列和網格(預定大小的二維數組)的結構體。

typedef struct 
    { 
     int row; 
     int column; 
     int (*matrix)[GRID_SIZE]; 
    } parameters; 

現在我創建一個

int grid[GRID_SIZE][GRID_SIZE] = { 
    {6, 5, 3, 1, 2, 8, 7, 9, 4}, 
    {1, 7, 4, 3, 5, 9, 6, 8, 2}, 
    {9, 2, 8, 4, 6, 7, 5, 3, 1}, 
    {2, 8, 6, 5, 1, 4, 3, 7, 9}, 
    {3, 9, 1, 7, 8, 2, 4, 5, 6}, 
    {5, 4, 7, 6, 9, 3, 2, 1, 8}, 
    {8, 6, 5, 2, 3, 1, 9, 4, 7}, 
    {4, 1, 2, 9, 7, 5, 8, 6, 3}, 
    {7, 3, 9, 8, 4, 6, 1, 2, 5}}; 
parameters *data = (parameters *) malloc(sizeof(parameters)); 
data->row = 1; 
data->column = 2; 
data->matrix = grid; // is this right? 

int** test = data->matrix; //this is wrong. 

我的目標是創建一個新線程時,在結構傳遞數據。當我在結構中創建二維數組並在之後使用它時,我對指針系統的工作方式無能爲力。任何幫助表示讚賞。

編輯...這是我的新代碼..看起來像它的工作! :)

parameters *data = malloc(sizeof(parameters)); //make sure to free thread after 
data->row = 1; 
data->column = 2; 
data->matrix = grid; 

int (*test)[GRID_SIZE] = data->matrix; 

printf("first value, %d\n", test[0][0]); 
+2

1)不要投malloc'和朋友的'結果在C 2)'INT **'不能引用2D數組。指針不是數組。 – Olaf

+2

[傳遞二維數組的結構]可能的副本(http://stackoverflow.com/questions/35614862/passing-a-2d-array-of-structs) – Olaf

+0

如果你傳遞數據到一個線程,那麼記住不會複製任何內容,並且您必須確保不會同時從兩個不同的線程同時訪問「網格」 –

回答

0

這樣的事情應該工作。 定義你的結構是這樣的:

typedef struct 
{ 
    int row; 
    int column; 
    int matrix[GRID_SIZE][GRID_SIZE]; 
} parameters; 

複製這樣的矩陣:

memcpy(data->matrix, grid, sizeof(grid));