gpt4 book ai didi

C段错误,不确定发生了什么

转载 作者:太空宇宙 更新时间:2023-11-04 06:41:48 25 4
gpt4 key购买 nike

我有以下代码,在第 68 行,出现格式错误。stack.c:68:警告:格式“%e”需要类型“float *”,但参数 3 的类型为“double *”

在输入 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);
}
}

最佳答案

刚刚快速查看了您的代码,我认为在压入第一个元素后您的栈顶指针设置为 0。现在在 StackShow() 方法中,您正在从这一行访问无效的内存位置:

 printf("%e ]\n", stackP->contents[stackP->top - 1]); // accessing invalid location stackP->contents[-1] 

这是一个 off-by-one error 对于数组内容。

关于C段错误,不确定发生了什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6894741/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com