如何初始化一个结构体地址到数组指针? [英] how to initialize a struct address to array pointer?

查看:102
本文介绍了如何初始化一个结构体地址到数组指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

具有此代码:

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

I would like to assign pointer struct Test ***p value of foo. So that I can manipulate with that pointer (declaring values in member of that struct). How to achieve this?

推荐答案

调用malloc后,ar[1](以及扩展名p[0][1])指向2个实例的数组. struct Test.所以ar[1][0]ar[1][1]都是结构实例.

After you call malloc, ar[1] (and by extension p[0][1]) points to an array of 2 instances of struct Test. So ar[1][0] and ar[1][1] are both struct instances.

似乎您希望它们成为指针,以便它们可以指向foo.因此,您需要额外的间接级别:

It seems like what you want is for them to be pointers so they can point to foo. So you need an extra level of indirection:

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);

这篇关于如何初始化一个结构体地址到数组指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆