1

我正在使用视觉工作室 2012。

我正在尝试使用单个数组实现 2 个堆栈。

我的 C 代码

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main()
 {
int arr[10], ch=1, *top1=&arr[0]-1, *top2=&arr[9]+1;


while(ch!=5)
{
printf("1. Push in Stack 1\n2. Pop from Stack 1\n3. Push in Stack 2\n4. Pop from Stack       2\n5.Exit");
scanf("%d",&ch);
    switch(ch)
    {
    case 1:
        if(top1+1 !=top2)
        {
        scanf("%d",*++top1);
        }
        else
        printf("stack is full");
break;
    case 2:
        if(top1 != &arr[0]-1)
        printf("%d",*top1);
        else
        printf("Stack is Empty");
break;
    case 3:
        if(top2-1 !=top1)
        {
        scanf("%d",*--top2);
        }
        else
        printf("stack is full");
break;
    case 4:
        if(top2 != &arr[9]+1)
        printf("%d",*top2);
        else
        printf("Stack is Empty");
break;
    case 5:
        return(0);
    }
}


return 0;

}  

代码运行正常, scanf("%d",*++top1);并且scanf("%d",*--top2);没有
接受输入。

scanf 的用法是否正确?

4

3 回答 3

3

您应该认真考虑警告,您忽略了:

warning: format ‘%d’expects type ‘int *’, but argument 2 has type ‘int’

为线scanf("%d", *++top1);scanf("%d", *--top2);

因为scanf() 使用%d格式字符串接受地址而不是值。因此,例如,表达式的值*++top1被视为不是有效地址的地址,因此这会在运行时导致未定义的行为。删除取消引用*指针,scanf()它将起作用。

于 2013-09-27T11:00:07.783 回答
1

scanf()第二个和第三个参数需要一个地址

如果您传递值而不是地址,您将收到以下警告

 warning: format â%dâ expects argument of type âint *â, but argument 2 has type âintâ [-Wformat]  

像这样修改

scanf("%d",*++top1); ==> scanf("%d",++top1);  
scanf("%d",*--top2); ==> scanf("%d",--top2);

编辑

您的 POP 实施不正确

1. pop1 you need to decrement top1
2. pop2 you need to increment top2
于 2013-09-27T10:59:58.753 回答
0

scanf()中,您只需要传递存储输入的内存地址。

但是您正在取消引用它。

例如。

改变

scanf("%d",*++top1); 

scanf("%d",++top1);
于 2013-09-27T10:59:49.073 回答