繁体   English   中英

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

[英]how to initialize a struct address to array pointer?

有这个代码:

#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;
}

我想分配foo的指针struct Test ***p值。 这样我就可以使用该指针进行操作(在该结构的成员中声明值)。 如何做到这一点?

调用malloc后, ar[1] (以及扩展名p[0][1] )指向struct Test的 2 个实例的数组。 所以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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM