这是非常愚蠢的问题,对不起,但我失去了很多时间:(。 我知道动态数组有问题,但我没有看到它无法正常工作的原因。
#include <stdio.h>
#include "Header.h"
#include <stdlib.h>
#include <iostream>
typedef struct Stack{
T* arr;
int num;
int size;
}Stack;
typedef struct Iterator {
Stack* stack;
}Iterator;
void initStackBitch(Stack* S) {
S->size = 25;
S->arr = (T*)(S->size * sizeof(*(S->arr)));
S->num = 0;
}
void ReinitStack(Stack* S) {
S->size = S->size * 2;
S->arr = (T*)realloc(S->arr, S->size * sizeof(*(S->arr)));
}
void push(Stack* S, T Element) {
if (IsStackFull(S)) {
ReinitStack(S);
cout << "Stack is remade";
}
else {
S->arr[S->num] = Element;
S->num++;
}
}
T pop(Stack* S) {
if (IsStackEmpty(S)) {
printf("Stack is Empty");
exit(2);
}
else {
S->num--;
return S->arr[S->num + 1];
}
}
int IsStackFull(Stack* S) {
if (S->num == S->size) {
return 1;
}
else return 0;
}
int IsStackEmpty(Stack* S) {
if (S->num == 0) {
return 1;
}
else return 0;
}
Iterator* CreateIterator(Stack* S) {
Iterator* iterator = (Iterator*)malloc(sizeof(Iterator));
iterator->stack = S;
return iterator;
}
bool HaveNext(Iterator* iterator) {
return iterator->stack->num != iterator->stack->size;
}
void GoNext(Iterator* iterator) {
if (HaveNext(iterator)) {
iterator->stack->arr = iterator->stack->arr + 1;
}
return;
}
void* GetValue(Iterator* iterator) {
if (HaveNext(iterator)) {
return iterator->stack->arr;
}
else exit(-1);
}
void PrintStack(Stack* stack) {
for (Iterator* iterator = CreateIterator(stack); HaveNext(iterator); GoNext(iterator)) {
cout << GetValue(iterator) << endl;
}
}
int main() {
Stack S;
initStackBitch(&S);
push(&S, 1);
push(&S, 2);
push(&S, 3);
pop(&S);
PrintStack(&S);
_fgetchar();
}
我知道这是错误的推动
答案 0 :(得分:0)
您必须在初始化时为arr
分配内存。初始化之后,Push将尝试进入未分配(未定义)的内存,从而导致崩溃。所以错误不在推动中:
void initStackBitch(Stack* S) {
S->size = 25;
S->arr = (T*)malloc(S->size * sizeof(*(S->arr)));
S->num = 0;
}