我试图用堆栈实现一个程序,但是堆栈没有显示出来

#include<stdio.h>
int size=0,count=1,test=0;

struct Car
{
    int registrationNo;
    char *name;
};

struct ParkingLot
{
    struct Car C[10];
};


struct stack
{
    struct ParkingLot P;
    int top;
} st;

int stfull()
{
    if(st.top >= size-1)
        return 1;
    else
        return 0;
}


void push(struct Car item) {
    st.top++;
    st.P.C[st.top] = item;
}



int stempty() {
    if (st.top == -1)
        return 1;
    else
        return 0;
}

void display() {
    int i;
    if (stempty())
        printf("\nStack Is Empty!");
    else {
    //printf("%d\n",st.top);
        for (i = 0; i<=st.top; i++)
            printf("\n%s", st.P.C[i].name);
    }
}



void Enter_ParkingLot()
{
    struct Car CC;
    int checkFull=stfull();
    if(checkFull==1)
        printf("Parking Lot is FUll\n");
    else
    {
        CC.registrationNo=count;count++;
        char ch[100];
        printf("Enter name of owner\n");
        scanf("%s",ch);

        CC.name=ch;

        push(CC);
    }
}



int main()
{
    printf("Enter size of Parking Lot\n");
    st.top=-1;

    scanf("%d",&size);
    Enter_ParkingLot();
    Enter_ParkingLot();
    display();
    return 0;
}

这是我在终端上的输入-
Enter size of Parking Lot
2
Enter name of owner
ABCD
Enter name of owner
EFGH

这是我的成果-
`@
`@

在输出中第一个@之前有一个空行。

最佳答案

如果您将struct Car中的指针字段分配给一个局部变量,它将不起作用,您需要像这样重新声明您的struct Car

struct Car
{
    int registrationNo;
    char name[100];
};

而不是
CC.name=ch;

这样做
strcpy(CC.name, ch);

另外,最好是写
scanf("%99s",ch);

为了防止溢出,在您的情况下,最好这样做
scanf("%99s", CC.name);

我修正了你的密码
#include <stdio.h>
#include <string.h>

struct Car
{
    int registrationNo;
    char name[100];
};

struct ParkingLot
{
    struct Car C[10];
};

struct stack
{
    struct ParkingLot P;
    int top;
} st;

int stfull(int size)
{
    if(st.top >= size - 1)
        return 1;
    return 0;
}

void push(struct Car item)
{
    st.P.C[++(st.top)] = item;
}

int stempty()
{
    if (st.top == -1)
        return 1;
    return 0;
}

void display()
{
    int i;
    if (stempty() != 0)
        printf("\nStack Is Empty!");
    else {
        for (i = 0 ; i <= st.top ; i++)
            printf("\n%s", st.P.C[i].name);
    }
}

int Enter_ParkingLot(int count, int size)
{
    struct Car CC;

    if (stfull(size) == 1)
        printf("Parking Lot is FUll\n");
    else
    {
        CC.registrationNo = count;

        printf("Enter name of owner\n");
        scanf("%99s", CC.name);

        push(CC);
    }

    return count + 1;
}

int main()
{
    int size = 0, count = 1;

    printf("Enter size of Parking Lot\n");

    st.top = -1;

    scanf("%d", &size);

    count = Enter_ParkingLot(count, size);
    count = Enter_ParkingLot(count, size);

    display();
    return 0;
}

我删除了全局变量,它们在不需要的地方。
我修正了一些毫无意义的错误。
我还应用了之前建议的与您的原始问题相关的修复方法。

关于c - 打印纸叠时出错,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28152636/

10-11 12:20