我已經閱讀了關於傳遞指向多維數組的指針的一些材料,但是我無法讓它爲我自己工作。如何將指針傳遞給抽象數據類型的多維數組
我有:
/* This code basically, in order, does this--or tries to:
- Create 2D array of cell structs
- Create info_pass detailing certain attributes of the 2D array
+ in particular, I am trying to include a pointer to the 2D array so that I
can pass the info_pass struct between functions and update the contents of
the 2D array in each function.
- The updating is done in struct info_pass* update(...){}
- ... however, in my full program, there are several other functions it is passed
to, so being able to pass a pointer that allows manipulation of the 2D array is
what I'm really after.
*/
struct info_pass {
/* stuff */
struct cell* master;
};
struct cell {
/* values */
/* lots of pointers to other cells */
};
struct info_pass* genesis() { /* creating an the multiD array */
/* stuff */
struct cell* (*cells)[width];
cells = malloc(sizeof(struct cell) * width * length);
struct info_pass* keycard = NULL;
keycard = malloc(sizeof(struct info_pass));
/* assign values to key card */
keycard->master = cells; /* problem here?! */ <==== (A)
/* update cells */
return keycard; /* therefore problem here too */
}
struct info_pass* update(struct info_pass* key) {
struct info_pass* keyRef = NULL;
keyRef = malloc(sizeof(struct info_pass));
keyRef = key; /* and of course here */
struct cell* home1 = NULL;
home1 = malloc(sizeof(struct cell));
/*here I want to update the multidimensional array*/ <===== (B)
/*... and then send it back ...*/
return keyRef;
}
錯誤@(A) =警告:分配從兼容的指針類型。
錯誤@(B) =錯誤:下標值既不是數組也不是指針。
只是希望推向正確的方向。
編輯
按ThePosey的建議,我會表現出更多的參與「錯誤代碼:下標值既不是指針也不array`s。我將在下面添加它,而不是將它放到上面的代碼示例中,以便爲將來的上下文保留原始問題的狀態。
struct info_pass* update(struct info_pass* key) {
/* passing data, including a pointer to a 2D array from info_pass */
/* struct then I want to access the 2D array and change it's contents */
/* contents and then send it back in another info_pass struct */
struct info_pass* keyRef = NULL;
keyRef = malloc(sizeof(struct info_pass));
keyRef = key; /* to pass the info back afterwards */
int len = keyRef->length;
int wid = keyRef->width;
struct cell* home1 = NULL;
home1 = malloc(sizeof(struct cell));
home1 = key->masterRef[len][wid]; /* to access and change the data */
int fate = 0;
int a = 0;
int b = 0;
for (a = 0; a < len; a++) {
for (b = 0; b < wid; b++) {
if (keyRef->masterRef[a][b].go_up.state == 1) {
/* just trying different styles of calls */
fate++;
} if (home1[a][b].go_down.state == 1) {
fate++;
} if (home1[a][b]->go_left->state == 1) {
fate++;
} if (home1[a][b]->go_right->state == 1) {
fate++;
/* there more calls to the array, and all generate the same error: */
/* subscripted value is neither array nor pointer */
它確實是一個二維數組!你的創建方法是否可以更容易地將指針傳遞給它?我不明白它將如何彌補這一困難。我將用簡要的解釋來編輯OP。 – d0rmLife 2013-02-19 03:17:48
「通過」是一個與函數參數相關的動詞。將一個指針傳遞給像數組這樣的數據指針可能意味着什麼? – 2013-02-19 03:29:34
@RonBurk指針指向這條數據,以便數據可以被操縱 - 它不是*參數。類似於鏈表。 – d0rmLife 2013-02-19 03:40:36