在结构“saf”中,我有数组“stack”,在结构“data”中,我有“pinx”,这是结构“data”的数组。我希望数组“stack”有一个成员“pinx”数组,但是我不知道如何从stack数组访问pinx的成员。我给你一个图像,这样你就会明白我想做什么。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct saf
{
  int head;
  void **stack;
  int size;
}exp1;

struct data
{
  int flag;
  char name[50];
};

 struct data *pinx;

void init(int n)
{

  pinx = malloc(sizeof(struct data) * n);
  exp1.stack = malloc(n);

}

void add()
{

 strcpy(pinx[0].name,"name");
 pinx[0].flag=0;
 exp1.stack[0]=&pinx[0];

}

int main()
{

 printf("Give size: ");
 scanf("%d",&exp1.size);
 init(exp1.size);
 add();

 return 0;
}

最佳答案

只是使用

void *stack;

在你的结构中。
exp1.stack = malloc(n); //is not needed

那么
exp1.stack = (void *)pinx;

以及访问元素
printf("%s \n", ((struct data *)exp1.stack)[0].name);

勇气

关于c - 具有多个成员的结构体数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22624447/

10-11 22:56
查看更多