有这样的代码。
#include <stdio.h>
#include <stdlib.h>
struct Test { char c; } foo;
int main (void) {
struct Test *ar[10];
struct Test *(*p)[10] = &ar; // var 'p' is kind of type "struct Test ***p"
*(*p+1) = malloc(sizeof(struct Test)*2); //alocated space in array p[0][1] for 2 structs
//Now I would like to have 'foo' from above in p[0][1][1]
// I cannot do "p[0][1][1] = foo", that is shallow copy
// which means "p[0][1][1].c = 'c'" will have no effect
// I need actually assign address to "&foo" to that pointer 'p'
// something like "(*(*p+1)+1) = &foo", but that is error:
//err: lvalue required as left operand of assignment
// reason:
p[0][1][1].c = 'c';
printf("%c\n", foo.c) // no output because foo is not in the array (its address was not assign to the pointer 'p')
return 0;
}
我想把指针 struct Test ***p
价值 foo
. 这样我就可以用该指针进行操作(在该结构的成员中声明值)。如何实现这个目标?
在你调用 malloc
, ar[1]
(进而 p[0][1]
)指向一个2 实例 的 struct Test
. 所以... ar[1][0]
和 ar[1][1]
都是结构实例。
似乎你想要的是让它们成为指针,这样它们可以指向 foo
. 所以你需要一个额外的间接层次。
struct Test **ar[10];
struct Test **(*p)[10] = &ar;
// allocate space at p[0][1] for 2 struct pointers
*(*p+1) = malloc(sizeof(struct Test *)*2);
p[0][1][1] = &foo;
p[0][1][1]->c = 'c';
printf("%c\n", foo.c);