【发布时间】:2017-06-23 20:06:23
【问题描述】:
我的 pop 没有弹出,老师提供了这段代码的骨架,我输入了 printf 语句,并且推送似乎正在工作,它似乎在到达 pop 一词时停止了。我知道我可能没有正确释放内存,所以我想我稍后会修复它(或者这可能是问题所在?) char** 真的让我对这个感到失望。 这个问题和这个Conflicting types for enum bool?是一样的 我想我班上更多的人遇到了问题。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct{
char** data; /* Array of strings representing the stack */
int top; /* Index of the top of the stack. top is -1 if the stack is
empty. */
int size; /* Number of elements that the stack can currently hold */
} Stack;
typedef enum { FALSE, TRUE } bool;
/* function prototypes */
Stack* create();
void deleteStack( Stack* ps );
void push( Stack* ps, char* str );
char* pop( Stack* s);
bool empty( Stack *s );
bool full( Stack *s );
int main(int argc, char *argv[])
{
FILE *in_file = fopen("data_a2.txt", "r");
Stack *s;
printf("CS 2123 Assignment 2\n");
if (in_file == NULL)
{
printf("File %s not found.\n", "data_a2.txt");
return -1;
}
char strBuffer[256];
s = create();
while(fscanf(in_file, "%s", strBuffer)!=EOF) {
printf("%s\n", strBuffer);
if(strcmp(strBuffer, "pop") == 0) {
pop(s);
} else {
push(s, strBuffer);
}
}
// free(s);
/* Uncomment next line once you get create working */
// deleteStack( &s );
fclose(in_file);
}
/* create: returns a new empty stack. */
Stack* create(){
Stack *s;
s = (Stack*)malloc(sizeof(Stack));
s->top = -1;
s->size = 10;
s->data = (char**)malloc(s->size * sizeof(char*));
return s;
}
/* deleteStack: deletes the memory associated with the given stack. */
void deleteStack( Stack* ps ){
while( ps->top>=0 ){
free( ps->data[ps->top] );
ps->top--;
}
free( ps->data );
}
/*
* push: takes a string parameter which is the value it pushes onto the
stack.
* It may also need to call realloc to expand the size of the stack before
completing the push.
*/
void push( Stack* s, char* str ){
char *newStr;
newStr = (char*)malloc(256);
strcpy(str, newStr);
if(full(s)){
s->size = 10;
s->data = (char**)realloc(s->data, s->size);
}
s->data[++s->top] = str;
free(newStr);
free(s->data);
//make new str malloc strcpy buffer
//realloc memory here s.data
}
/* pop: returns the string that was removed from the stack. */
char* pop( Stack* s){
if(empty(s)) {
return NULL;
}
printf("# of elements after popping: %d, string popped: %s\n",s->top + 1, s-
>data[s->top]);
return s->data[s->top--];
}
/* empty: returns TRUE if the stack has no elements, otherwise FALSE. */
bool empty( Stack *s ){
if(s->top == -1) {
return TRUE;
}
return FALSE;
}
/* full returns TRUE if the stack does not have any room left, otherwise
FALSE. */
bool full( Stack *s ){
if (s->top == s->size - 1) {
return TRUE;
}
return FALSE;
}
【问题讨论】:
-
printf里不应该是
s->top - 1吗... -
你的
strcpy参数被颠倒了。应该是strcpy(newstr, str)。