关于栈的问题
我的目的是将逐个浮点数压入栈 然后每压入一个数就将栈中的全部元素打印出来
代码如下:
- C/C++ code
#define OK 0x0001#define ERROR 0x0000#define TRUE 0x0001#define FALSE 0x0000#define INFEASIBLE 0xFFFF#define STACK_INIT_SIZE 10#define STACKINCREMENT 10#include <stdio.h>#include <stdlib.h>#include <string.h>#include <math.h>#include <malloc.h>typedef int Status;typedef float SElemType;typedef struct{ SElemType *base; SElemType *top; Status stacksize;}SqStack;void InitStack(SqStack S){ S.base = (SElemType *)malloc(STACK_INIT_SIZE * sizeof(SElemType)); if (!S.base) { printf("Memory allocation failure!"); exit(OVERFLOW); } S.base = S.top; S.stacksize = STACK_INIT_SIZE;}Status GetTop(SqStack S, SElemType *e){ if (S.base == S.top) return (ERROR); *e = *(S.top - 1); return (OK);}Status Push(SqStack S, SElemType e){ if (S.top - S.base == S.stacksize) // Stack fulls, Add storage space { S.base = (SElemType *) realloc (S.base, (S.stacksize + STACKINCREMENT * sizeof(SElemType))); S.top = S.stacksize + S.base; S.stacksize += STACKINCREMENT; } *S.top++ = e; return OK;}Status Pop(SqStack S, SElemType *e){ if (S.base == S.top) { printf("The Stack is Empty!"); return ERROR; } *e = *--S.top; return OK;}int main(){ SqStack S; int i = 0, count = 0; float fElem; InitStack(S); while (1) { scanf("%f", &fElem); Push(S, fElem); count++; // for (i = 0; i < count; i++) printf("%d\n", count); printf("%f\n", *(S.top - 1)); } return 0;}问题是
1.编译后提示warning C4700: local variable 'S' used without having been initialized
SqStack S;定义后难道还要自己给S赋值吗?
2.
如果把
typedef struct
{
SElemType *base;
SElemType *top;
Status stacksize;
}SqStack;中的SqStack改成*SqStack 并且把程序中的.换成->后提示更多错误 为什么
3
typedef struct
{
SElemType *base;
SElemType *top;
Status stacksize;
}SqStack, *SqStack;
和
typedef struct
{
SElemType *base;
SElemType *top;
Status stacksize;
}*SqStack, SqStack;
有区别吗 他们都在实现个什么功能?
[解决办法]
文不对题。
问题1,是因为你初始化的函数 没写好,编译时候 发现S没初始化,当然有警告。
InitStack 传 S 地址进行初始化可以解决,InitStack方法传入参数要修改一下。
问题2,仅仅修改typedef 是肯定还有问题的,
修改之后 SqStack S 意味着:S是个指向 SqStack 结构体的指针。
而指针没分配空间,你就调用 InitStack 进行初始化,肯定要出错的。
问题3,区别肯定有个:
第一个 SqStack 是指向 SqStack 结构体的指针类型。
第二个 SqStack 是SqStack 结构体的类型。
-------------
总之,我的建议:
- C/C++ code
typedef struct SqStack_t{ SElemType *base; SElemType *top; Status stacksize;}SqStack, *LPSqStack;