Full disclosure: this is for an assignment. I'm not looking for explicit answers, but a little guidance.
I'm having a hard time initializing my stack in C. Specifically, I can't seem to get it to properly push new elements onto the stack. I know my push/pop/etc functions are correct (they were provided) but I fear that I'm not looking at this correctly.
This is a basic attempt at reading a string and determining if it is "balanced" (all parentheses, curly and square brackets have partners and appear in the correct order.) As far as I can tell, it isn't a problem with my logic and I believe the syntax is correct, so I'm kind of at a loss for ideas...
Here's my attempt at the implementation:
int isBalanced(char* s) {
struct DynArr *string;
string = newDynArr(50);
while (nextChar(s) != '\0') {
if ((nextChar(s) == '(') || (nextChar(s) == '{') || (nextChar(s) == '[')) {
pushDynArr(string, nextChar(s));
}
if (nextChar(s) == ')') {
if (topDynArr(string) != '(') {
return 0;
} else popDynArr(string);
}
if (nextChar(s) == '}') {
if (topDynArr(string) != '{') {
return 0;
} else popDynArr(string);
}
if (nextChar(s) == ']') {
if (topDynArr(string) != '[') {
return 0;
} else popDynArr(string);
}
}
if (isEmptyDynArr(string)) {
printf("The stack is empty\n");
return 1;
} else return 0;
}
The output always prints "The stack is empty" and returns true, despite me giving it unbalanced strings. I've probably been looking at this for too long and can't recognize the obvious. I'd appreciate any help you can lend. I don't need explicit answers, but a push in the right direction would be enough.
Edit: Here are the functions that have been requested...
int isEmptyDynArr(DynArr *v)
{
if(v->size == 0) {
return 1;
}
else return 0;
}
DynArr* newDynArr(int cap)
{
assert(cap > 0);
DynArr *r = (DynArr *)malloc(sizeof( DynArr));
assert(r != 0);
initDynArr(r,cap);
return r;
}
void pushDynArr(DynArr *v, TYPE val)
{
assert(v != 0);
addDynArr(v, val);
}
void popDynArr(DynArr *v)
{
assert(v != 0);
assert(isEmptyDynArr(v) == 0);
v->size--;
}
TYPE topDynArr(DynArr *v)
{
assert(v != 0);
assert(isEmptyDynArr(v) == 0);
return v->data[v->size - 1];
}
char nextChar(char* s)
{
static int i = -1;
char c;
++i;
c = *(s+i);
if ( c == '\0' )
return '\0';
else
return c;
}
isEmptyDynArr()DynArrstructure? And thenextCharand thepushDynArr/popDynArr/topDynArr/isEmptyDynArrfunctions?