简体   繁体   中英

Array of structs with multiple members

In struct "saf" i have the array "stack" and in struct "data" i have "pinx" which is the array of struct "data" . I want to the array "stack" to have as members the "pinx" array, but i don't know how can i have access from stack array to the members of pinx. I provide you an image so you will understand what i want to do.

在此处输入图片说明

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

If I understand correctly, you need a cast:

struct data* getElement(struct saf* from, int i)
{
    void* vp = from->stack[i];
    struct data* d = (struct data*)(vp);
    return vp;
}

So you can then write:

void checkGet()
{
    struct data* e1 = getElement(&exp1, 0);
    printf("%d %s\n", e1->flag, e1->name);
}

Of course, some error checking would be good - the accessor should check i is in range and probably return 0 if not.

Just use

void *stack;

in your saf struct.

exp1.stack = malloc(n); //is not needed

Then

exp1.stack = (void *)pinx;

and accessing elements

printf("%s \n", ((struct data *)exp1.stack)[0].name);

valter

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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