积极答复者
整型数输出问题

问题
-
整型数输出显示成8-842105451 7-842105451之类的,请同志们指点一二。
下面是我的源代码
//求非减整数表中的众数
#include "stdio.h"
#include "stdlib.h"
#define Max 1000
#define Increase 10
#define N 20typedef struct{
int *base;
int top;}Stack;void Init(Stack *S);//构建一个空栈
void Push(Stack *S,int number);//数据入栈
void Pop(Stack *S,int *p);//数据出栈
void Clear(Stack *S);//清空栈int main()
{
int state = 1,i,k = 0,max = 1;
int *p,value;
int array1[N] = {1,3,3,3,5,6,6,6,7,7,7,8,8,8,9,9,9,10,20,20};
Stack stack,*S;S = &stack;
p = &value;
Init(S);
for(i = 1; i < N; i ++)
{
if(array1[i] == array1[i - 1])
{
state ++;
}
else
{
if(state > max)
{
max = state;
Clear(S);
Push(S,array1[i - 1]);
}
else
{
if(state == max)
{
Push(S,array1[i - 1]);
}
}
state = 1;
}
}
for(i = 0; i < N; i ++)
{
printf("% d",array1[i]);
}
printf("\n");
while(S->top > 0)
{
Pop(S,p);
printf("% d",*p);
}
printf("\n");
return 0;}
void Init(Stack *S) //构建一个空栈
{
S->base = (int *)malloc(Max * sizeof(int));
S->top = -1;
}
void Push(Stack *S,int number)//数据入栈
{
if (S->top >= Max)
{
int *newbase;
newbase = (int *)realloc(S->base,(Max + Increase) * sizeof(int));
S->base = newbase;
}
S->base[++ S->top] = number;
S->top ++;
}
void Pop(Stack *S,int *p)//数据出栈
{
if (-- S->top < 0)
{
printf("Error:Illegal opreation,The Stack is Empty\n");
}
else
{
*p = S->base[S->top];
}
}
void Clear(Stack *S) //清空栈
{
S->top = -1;
}
答案
-
你好,
我根据你的代码发现,您在Push的方法中对 S->top进行了2次赋值:
S->base[++ S->top] = number;
S->top ++;
例如,array1[3] == array1[2] 都为3时,需要进行清空栈和入栈操作。当程序进入Push 方法S->top在S->base赋值的时候已经被累加。因此在你完成所有的入栈操作的时候,S->base[] 是被间隔的赋值。你可以用for(int tmp = 0; tmp < S->top; tmp++) printf(" %d ", S->base[tmp]); 来查看具体的赋值情况。
希望我的回答对你的疑问有所帮助。
Rob Pan [MSFT]
MSDN Community Support | Feedback to us
Get or Request Code Sample from Microsoft
Please remember to mark the replies as answers if they help and unmark them if they provide no help.
- 已标记为答案 战和姜 2011年5月10日 9:55
全部回复
-
你好,
我根据你的代码发现,您在Push的方法中对 S->top进行了2次赋值:
S->base[++ S->top] = number;
S->top ++;
例如,array1[3] == array1[2] 都为3时,需要进行清空栈和入栈操作。当程序进入Push 方法S->top在S->base赋值的时候已经被累加。因此在你完成所有的入栈操作的时候,S->base[] 是被间隔的赋值。你可以用for(int tmp = 0; tmp < S->top; tmp++) printf(" %d ", S->base[tmp]); 来查看具体的赋值情况。
希望我的回答对你的疑问有所帮助。
Rob Pan [MSFT]
MSDN Community Support | Feedback to us
Get or Request Code Sample from Microsoft
Please remember to mark the replies as answers if they help and unmark them if they provide no help.
- 已标记为答案 战和姜 2011年5月10日 9:55