1

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;
}
1
  • exp1.stack = malloc(n); is probably an error, I think you meant exp1.stack = malloc(n * sizeof *exp1.stack), which will let you have n pointers in that array. Commented Mar 25, 2014 at 3:11

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

1

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.

3 Comments

This is not what i want. I need something like that : For example i need to print the flag from the second element of stack which is pinx[1].flag , exp1.stack->pinx[1]->flag (-> not pointer only just an arrow so i can make you understand what i want)
To get the second element, call getElement(exp1, 1)? Not sure what else you could want.
i want to use stack array only. I want to have access to flag and name through stack , like this : exp1.stack[i]=pinx[i] and from there to gain access to the members of pinx

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.