我有以下代码,并在第68行,我得到一个格式错误。 stack.c:68: warning: format ‘%e’ expects type ‘float *’, but argument 3 has type ‘double *’
C段错误,不知道是怎么回事
在输入push 4
上,它得到一个段错误。不知道他们是否有关系。请帮忙!
#include <stdio.h>
#include <stdlib.h>
#define OFFSET '0'
#define DIM1 7
#define DIM2 5
#define RES_SIZE 1000
//typedef double double;
typedef struct {
double *contents;
int maxSize;
int top;
} stackT;
void StackInit(stackT *stackP, int maxSize) {
double *newContents;
newContents = (double *)malloc(sizeof(double)*maxSize);
if (newContents == NULL) {
fprintf(stderr, "Not enough memory.\n");
exit(1);
}
stackP->contents = newContents;
stackP->maxSize = maxSize;
stackP->top = -1;
}
void StackDestroy(stackT *stackP) {
free(stackP->contents);
stackP->contents = NULL;
stackP->maxSize = 0;
stackP->top = -1;
}
int StackIsEmpty(stackT *stackP) { return stackP->top < 0; }
int StackIsFull(stackT *stackP) { return stackP->top >= stackP->maxSize-1; }
void StackPush(stackT *stackP, double element) {
if(StackIsFull(stackP)) {
fprintf(stderr, "Can't push element: stack is full.\n");
exit(1);
}
stackP->contents[++stackP->top] = element;
}
double StackPop(stackT *stackP) {
if(StackIsEmpty(stackP)) {
fprintf(stderr, "Can't pop element: stack is empty.\n");
exit(1);
}
return stackP->contents[stackP->top--];
}
void StackShow(stackT *stackP) {
int i;
printf("[ ");
for (i = 0; i < stackP->top - 1; i++) {
printf("%e, ", stackP->contents[i]);
}
printf("%e ]\n", stackP->contents[stackP->top - 1]);
}
double shell(char* s1, double arg) {
printf("> ");
scanf("%s %f%*c", s1, &arg);
return arg;
}
int main() {
//char cmds[DIM1][DIM2] = {{"push"}, {"pop"}, {"add"}, {"ifeq"}, {"jump"}, {"print"}, {"dup"}};
stackT res;
StackInit(&res, RES_SIZE);
char cmd[DIM2]; double arg = 0;
arg = shell(cmd, arg);
if (StringEqual(cmd, "push")) {
StackPush(&res, arg);
StackShow(&res);
}
}
错误消息的含义正是它所说的。你不能使用'double'变量和'float'格式说明符。使用“%lf”。在StackShow中还有一个错误的错误,而且你忽略了堆栈可能为空的事实。 –
我在68上将它改为'%lf',segfault仍然存在,StackShow有什么问题? – tekknolagi
您是否尝试过在调试器中运行代码?它会马上给你答案... –