我已经阅读了一些关于将指针传递给多维数组的材料,但我无法让它为自己工作。
我有:
/* 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 的建议,我将展示更多涉及“错误:下标值既不是指针也不是数组”的代码。我将在下面添加它而不是将其放入上面的代码示例中,以便为将来的上下文保留原始问题的状态。
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 */