我有一个使用单指针完成的堆栈程序。现在,我必须使用类型为double
的双指针来引用类型为double的数组中元素的索引。我做了一个随机数生成器,试图满足这4个条件。
- 堆栈将以一个double数组的形式出现
- push()和pop()的第三个参数将采用
double **top
,即存储堆栈上当前顶部元素的地址的指向指针的指针。提示:在这些函数中,在堆栈更新时修改*top - 将为您创建一个全局整数变量myerror。其值可以是STACK_FULL、STACK_EMPTY和NORMAL。在push()和pop()函数中使用此变量来通知main()函数操作的状态
- 在main()中测试函数。请参阅骨架代码堆栈.c中的详细信息
我不知道如何将双指针传递给push函数。那是双重型。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <time.h>
#define STACK_SIZE 10
#define STACK_FULL -2
#define STACK_EMPTY -1
#define NORMAL 0
int myerror = NORMAL;
void push(double [], // input/ouput - the stack
double, // input - data being pushed onto the stack
double **, // input/output - pointer to pointer to the top of stack
int); // constant - maximum capacity of stack
double // output - data being popped out from the stack
pop(double [], // input/output - the stack
double **); // input/output - pointer to pointer to top of stack
void push(double stack[], double item, double **top, int max_size)
{
if(**top==(max_size-1))
{
printf("Stack is Fulln");
return;
}
else
{
}
return;
}
double pop(double stack[],
double **top){
}
int main(){
double s[STACK_SIZE];
double *s_top = NULL;
int max_size=STACK_SIZE;
double **top;
top=&s_top;
srand(time(NULL));
int i;
double randNum=0.0;
for(i=0; i<STACK_SIZE; i++)
{
randNum = 94.0*(rand()/(RAND_MAX + 1.0));
randNum = randNum + 33.0;
printf("nRandom double : %fn ",randNum);
// push(s, randNum, top, max_size);
}
printf("-----------n");
// Keep pushing doubles equivalent to chars randomly picked between '!'(33) and '~'(126)
// to the stack until it is full.
// Print each double before each pushing.
// Keep popping out doubles from the stack until it is empty
// Print each double after each popping.
// Repeat above until the user says 'no'.
return 0;
}
调用push时,传递栈顶指针的地址。看起来s_top
是指向堆栈顶部的指针,所以在调用push
时,您应该使用:
push(s, /* the entire stack */
randNum, /* the number being added to the stack */
&s_top, /* pass the ADDRESS of the pointer which points to the top-of-stack */
max_size); /* the maximum size of the stack - could also just pass STACK_SIZE */
+1关于这个问题,因为这是一个很好的方法来寻求帮助解决家庭作业问题。你并不是要求解决整个问题,只是在你不理解的事情上寻求帮助。
分享并享受。
样本代码
void push(double stack[], double item, double **top, int max_size){
if(*top == stack + max_size){
printf("Stack is Fulln");
myerror = STACK_FULL;
return;
}
**top = item;
++*top;
myerror = NORMAL;
}
int main(){
double s[STACK_SIZE];
double *s_top = s;
double randNum=0.0;
srand(time(NULL));
while(myerror != STACK_FULL){
randNum = 94.0*(rand()/(RAND_MAX + 1.0));
randNum = randNum + 33.0;
printf("nRandom double : %fn ",randNum);
push(s, randNum, &s_top, STACK_SIZE);
//printf("%p, <%f>n", (void*)s_top, s_top[-1]);
}
printf("-----------n");
return 0;
}