Manuel Pap
Manuel Pap

Reputation: 1399

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.

enter image description here

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

Upvotes: 1

Views: 109

Answers (2)

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

Upvotes: 1

Keith
Keith

Reputation: 6834

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.

Upvotes: 1

Related Questions