简体   繁体   中英

Stack that contains Pointers to other Structs

I tried making a Stack that contains Pointers(meaning adresses) that point to some other kind of structs(Prof or Stud). But I can't seem to manage it. The errors were infinite. Here's the code:

     struct MyStack
     {
        int head;
        void **stack;
        int size;
     };

     struct stud
     {
        char flag;
        char fname[50];
        int semester;
     };
     struct prof
     {
        char flag;
        char fname[50];
        char course[30];
     };
int InitStack(int size,struct MyStack *stack);

int InitStack(int size,struct MyStack *stack)
{
     stack->size = size;
     *stack->stack=(int *) malloc(size*sizeof(int) ); //Is this RIGHT? 
     stack->head=-1;
     return 0;
}
int main()
{
     int size,sel;

     size = GiveSize();
     struct MyStack NewStack;
     InitStack(size,&NewStack);

     do{
     sel=Menu();
     Select(sel,NewStack.head,&NewStack);
     }while (sel!=0);



     return 0;
 }

How I can push pointers(that point to studs and profs) to the stack?

Heres the code:

int CreateStud(struct MyStack *stack,char *name,int sem,int *head,int n)
{
struct stud newStud;
int thead=*head;

newStud.flag='s';
strcpy(newStud.fname,name);
newStud.semester=sem;
Push(stack,&thead,&newStud,n);
*head=thead;

return 0;
}
int Push(struct MyStack *stack,int *head, void *elem,int n)
{
if(*head>=n-1)
    return 0;
stack->stack[++*head]=elem;

return 1;
 }

Your InitStack function should be

int InitStack(int size,struct MyStack *stack)
{
     stack->size = size;
     stack->stack= malloc(size * sizeof(void*));
     stack->head=-1;
     return 0;
}

The push function should be something like

int Push(struct MyStack *stack, void *str)
{
     /* Check if stack is full */
     stack->head++;
     stack->stack[stack->head] = str;
     return 0;
}

The you can use it as

struct stud s1;
struct prof p1;

Push(&NewStack, &s1);
Push(&NewStack, &p1);

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