包含指向其他结构的指针的堆栈

时间:2014-04-01 14:47:36

标签: c pointers struct stack

我尝试制作一个包含Pointers(意思是地址)的Stack,它指向其他一些结构(Prof或Stud)。但我似乎无法管理它。错误是无限的。这是代码:

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

如何将指针(指向studs和profs)推送到堆栈?

下面是代码:

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

1 个答案:

答案 0 :(得分:0)

您的InitStack功能应该是

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

推送功能应该类似于

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

您可以将其用作

struct stud s1;
struct prof p1;

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