如何将一个结构地址初始化为数组指针?

问题描述 投票:0回答:1

有这样的代码。

#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. 这样我就可以用该指针进行操作(在该结构的成员中声明值)。如何实现这个目标?

c arrays pointers struct
1个回答
1
投票

在你调用 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);
© www.soinside.com 2019 - 2024. All rights reserved.