I'm trying to get brackets to match. What needs to be matched is the '()', '[]', '{}' and '[{}]' is supposed to output true. I don't want it to work for the cases such as '[{]}' or '[{}'. Though, right now my code is not outputting yes for the correct match even when it should be true.
Code (updated):
int booleanBalanceBracket(aStack *theStack){
aStack *balanceStack = NULL;
while(theStack){
if(theStack->token == '[' || theStack->token == '{' || theStack->token == '(')
balanceStack = pushBracket(theStack->token, balanceStack);
else if(theStack->token == ']' || theStack->token == '}' || theStack->token == ')'){
if(balanceStack == NULL)
return 0;
else
balanceStack = popBracket(balanceStack);
}
theStack = theStack->nextItem;
}
if(balanceStack == NULL){
return 1;
}else{
return 0;
}
}
int isMatching(int token1, int token2){
if(token2 == '(' && token1 == ')')
return 1;
else if(token2 == '{' && token1 == '}')
return 1;
else if(token2 == '[' && token1 == ']')
return 1;
else
return 0;
}
Try this simple algorithm:
for each char c in the input
if opener
push on stack
else if closer
if stack is empty or doesn't match
return false
else
remove top of stack
return true if stack is empty, else false
This can be slightly optimized to avoid the empty stack checks and also to avoid an explicit check for EOF by pushing EOF onto the stack initially, and matching EOF to EOF.
your code problem is this line
balanceStack = popBracket(balanceStack);
Does not receive a value obtained by pop. It is also necessary to compare the value popped.
The Example of a simple string
bool booleanBaranceBracket(const char *s){
static const char *left = "{([";
static const char *right = "})]";
size_t len = strlen(s);
char *p, stack[len];
int sp = -1;
int i;
for(i=0;i<len;++i){
if(p = strchr(left, s[i]))
stack[++sp] = s[i];
else if(p = strchr(right, s[i])){
char ch;
if(sp == -1) return false;
ch = stack[sp--];
if(ch != left[p - right]) return false;
}
}
return sp == -1;
}
Related
The giver code is for converting infix to postfix using stack. I tried it everywhere no errors or warning were shown except for one time there was a segmentation fault on my school's computer. If anyone can explain the correct way to write the code it'll be very helpful as I'm unable to find.
In code we scan the infix expression and check if it's an operator and then if it is an operator we push it to stack and character or digit go to an array. We then pop the operator from the stack if we find another operator of more precedence than the previous pushed operator and we keep popping till we get less precedence operator in stack and append it to the array that is also our output.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include<ctype.h>
struct stack
{
int size;
int top;
char *arr;
};
int stacktop(struct stack *sp)
{
return sp->arr[sp->top];
}
void push(struct stack *ptr, char val)
{
if (ptr->top == ptr->size - 1)
{
printf("Stack is full\n");
}
else
{
ptr->top++;
ptr->arr[ptr->top] = val;
}
}
char pop(struct stack *ptr)
{
int a;
if (ptr->top == -1)
{
printf("\n");
}
else
{
a = ptr->arr[ptr->top];
ptr->top--;
return a;
}
}
int isoperator(char symbol)
{
if (symbol == '^' || symbol == '*' || symbol == '/' || symbol == '+' || symbol == '-')
{
return 1;
}
else
{
return 0;
}
}
int precedence(char symbol)
{
if (symbol == '^')
{
return (3);
}
else if (symbol == '*' || symbol == '/')
{
return (2);
}
else if (symbol == '-' || symbol == '+')
{
return (1);
}
else
{
return (0);
}
}
char *infix_to_postfix(char *infix)
{
struct stack *sp = (struct stack *)malloc(sizeof(struct stack));
sp->size = 50;
sp->top = -1;
sp->arr = (char *)malloc(sp->size * sizeof(char));
char *postfix = (char *)malloc(strlen((infix) + 1) * sizeof(char));
int i = 0, j = 0, x = 0;
while (infix[i] != '\0')
{
if (infix[i] == '(')
{
push(sp, infix[i]);
}
else if( isdigit(infix[i]) || isalpha(infix[i])){
postfix[j]=infix[i];
j++;
}
else if (isoperator(infix[i])==1)
{
x=pop(sp);
while(isoperator(x)==1 && precedence(x)>=precedence(infix[i])){
postfix[j]=x;
j++;
x=pop(sp);
}
push(sp, x);
push(sp, infix[i]);
}
else if (infix[i] == ')')
{
x = pop(sp);
while (x != '(')
{
postfix[j] = x;
j++;
x = pop(sp);
}
}
i++;
}
while (!(sp->top == -1))
{
postfix[j] = pop(sp);
j++;
}
postfix[j] = '\0';
return postfix;
}
int main()
{
char *infix;
printf("Enter your expression\n");
scanf("%s",infix);
printf("Postfix is %s", infix_to_postfix(infix));
return 0;
}
The pointer variable char *infix doesn't point to anything so it's not about VSCode and other compilers. It's complete luck that it's working on VSCode.
You should allocate some memory either statically char infix[100] or dynamically char *infix = (char *)malloc(100).
Also, you have a problem with pop function. You shouöd always return a char from this function not only under certain conditions.
So I have an IsNumber() function which checks if an user input is a number or not, if it isn't the the program stops, however the function just isn't working for some reason.
Here is where it's implemented:
bool IsNumber(const char* pStr);
int main()
{
int user;
char decision;
char * str[256] = {user};
bool valid;
scanf("%d",&user);
clear_stdin(); // function to remove
sprintf(str, "%d", user); // to convert input into string so to validate number with function IsNumber
valid = IsNumber(str);
if (valid == false)
{
printf("Entered input is not a number, exiting now.");
exit(1);
}
}
And here is the function itself:
bool IsNumber(const char* pStr)
{
if(NULL == pStr || *pStr == "\0")
return false;
int dotCount = 0;
int plusCount = 0;
int minusCount = 0;
while (*pStr)
{
char c = *pStr;
switch(c)
{
case '.':
if (++dotCount > 1)
return false;
break;
case '-':
if (++minusCount > 1)
return false;
break;
case '+':
if (++plusCount > 1)
return false;
default:
if (c < '0' || c > '9')
return false;
}
pStr++;
}
return true;
}
your function does not check for the most of the errors (for example 345+456). You need to remember that some chars can be only at the particular places to make number valid.
Here you have a bit better one (very simple for the sake of simplicity of the answer).
int isNumber(const char *str)
{
int result = 1;
int dotFound = 0;
const char *saved = str;
if(str || *str)
{
while(*str && result)
{
if(*str == '-' || *str == '+')
{
if(str != saved) result = 0;
}
else
{
if(*str == '.')
{
if(dotFound) result = 0;
dotFound = 1;
}
else
{
if(!isdigit(*str)) result = 0;
}
}
str++;
}
}
return result;
}
Your test idea is wrong. sprintf will always print a valid int number. it will also never generate the string with the dot '.' inside.
https://godbolt.org/z/d_Bah9
There are several issues with your code:
The line
char *str[256] = {user};
You are declaring an array of 256 pointers to char, none of them is initialized along your code, so they point to nothing, furthermore you are trying to assign an int variable to a char pointer.
The line
sprintf(str, "%d", user);
str is not a valid argument, you could use str[0], but, again, str[0] points to nowhere.
The line
if(NULL == pStr || *pStr == "\0")
^^^^
You are comparing a single character with a string, a valid comparison would be:
if(NULL == pStr || *pStr == '\0')
^^^^
Other issues are:
A missing break in case '+'.
char decision is never used.
Below is the code to determine balancing of symbol.
If the expression is balanced then it should print appropriate message. E.g:
((A+B))+(C+D)) --> Balanced
((A+B)+(C+D) ---> Unbalanced
((A+B)+(C+D}) --> Unbalanced
Here is the code
#include <stdio.h>
#include <stdlib.h>
struct Stack {
char data;
struct Stack *next;
};
void push(struct Stack **top, char data) {
struct Stack *new_node;
if (*top == NULL) {
new_node = malloc(sizeof(struct Stack));
new_node->data = data;
new_node->next = *top;
*top = new_node;
} else {
new_node = malloc(sizeof(struct Stack));
new_node->data = data;
new_node->next = *top;
*top = new_node;
}
}
char pop(struct Stack **top, int flag) {
if (*top != NULL && flag == 0) {
printf("\n Expression is In-Valid :) \n");
return '\0';
}
if (*top == NULL && flag == 1) {
printf("\n Unbalanced Expression \n");
return '\0';
}
if (*top != NULL && flag == 1) {
struct Stack *temp = *top;
char op;
op = (*top)->data;
*top = (*top)->next;
free(temp);
return op;
}
}
/*
void display(struct Stack *top) {
struct Stack *temp = top;
while (temp) {
printf("\n %c", temp->data);
temp = temp->next;
}
}
*/
int main(void) {
struct Stack *top = NULL;
int i = 0;
char str[] = "((A+B)+[C+D])", op;
printf("\n Running the programe to check if the string is balanced or not ");
for (i = 0; str[i] != '\0'; ++i) {
if (str[i] == '(' || str[i] == '[' || str[i] == '{' || str[i] == '<')
push(&top, str[i]);
else
if (str[i] == ')' || str[i] == ']' || str[i] == '}' || str[i] == '>') {
op = pop(&top, 1);
if ((op == '(' && str[i] == ')') ||
(op == '[' && str[i] == ']') ||
(op == '{' && str[i] == '}') ||
(op == '<' && str[i] == '>')) {
continue;
} else {
printf("\n The expression is un-balanced \n");
break;
}
}
}
pop(&top, 0);
return 0;
}
But it does not give the desired output. I have debugged the code but was not able to find the issue.
How can I have it print the appropriate message ?
You should immediately clean the stack and stop processing as soon as you detect something unbalanced, and print "Balanced" when you reach return 0. And you should print "Unbalanced" from one single place in your code.
And it is bad that one branch of pop does not return a value when it is declared to return one.
So, pop could become:
char pop(struct Stack **top,int flag)
{
if(*top!=NULL && flag==0)
{
return '\0';
}
if(*top==NULL && flag ==1)
{
return '\0';
}
if(*top!=NULL && flag==1)
{
struct Stack *temp=*top;
char op;
op=(*top)->data;
*top=(*top)->next;
free(temp);
return op;
}
// *top == null && flag == 0
return 'O'; // for OK
}
I would add a clean method - not required because program exit cleans the stack, but I do prefer that:
void clean(struct Stack *top) {
struct Stack *next;
while (top != NULL) {
next = top->next;
free(top);
top = next;
}
}
And some changes in main:
int main(void)
{
struct Stack *top=NULL;
int i=0, err=0;
...
else
{
err = 1;
break;
}
}
}
if (err || (pop(&top,0) == '\0')) {
printf("\n The expression is un-balanced \n");
clean(top);
// return 1; optionally if you want to return a different value to environment
}
else {
printf("\n The expression is balanced \n");
}
return 0;
}
Your pop function is wrong.
You have not handled if top is null and flag is 0. It might also be a case.
Secondly, why do you **top in your push\pop signature when you should be passing top in it. I think it should have *top in its signature.
Also, why you use if in push. Its not needed. You are essentially doing same thing.
You can do this simply by simple modification in this code. I take it from Find maximum depth of nested parenthesis in a string this. It's also help for knowing details. I think it's helpful to you
#include <iostream>
using namespace std;
// function takes a string and returns the
// maximum depth nested parenthesis
int maxDepth(string S)
{
int current_max = 0; // current count
int max = 0; // overall maximum count
int n = S.length();
// Traverse the input string
for (int i = 0; i< n; i++)
{
if (S[i] == '(')
{
current_max++;
// update max if required
if (current_max> max)
max = current_max;
}
else if (S[i] == ')')
{
if (current_max>0)
current_max--;
else
return -1;
}
}
// finally check for unbalanced string
if (current_max != 0)
return -1;
return max;
}
// Driver program
int main()
{
string s = "( ((X)) (((Y))) )";
if (maxDepth(s) == -1)
cout << "Unbalance";
else
cout << "Balance";
return 0;
}
Time Complexity : O(n)
Auxiliary Space : O(1)
Thanks for the suggestions. Here is my below working code of the same problem
#include<stdio.h>
#include<stdlib.h>
struct Stack{
char data;
struct Stack *next;
};
void push(struct Stack **top,char data)
{
struct Stack *new_node;
new_node=malloc(sizeof(struct Stack));
new_node->data=data;
new_node->next=*top;
*top=new_node;
}
int compare(char str,char op)
{
if( (op == '(' && str == ')') || (op == '{' && str == '}') || (op == '[' && str == ']') || (op == '<' && str == '>') )
return 1;
else
return 0;
}
int pop(struct Stack **top,char str)
{
char op,ret;
struct Stack *temp=*top;
if(*top==NULL)
return 0;
else if(*top!=NULL)
{
// Pop the element and then call comapre function
op=(*top)->data;
free(temp);
*top=(*top)->next;
return(ret=compare(str,op));
}
}
void display(struct Stack *top)
{
struct Stack *temp=top;
while(temp!=NULL)
{
printf("%c ",temp->data);
temp=temp->next;
}
printf("\n");
}
int isNotEmpty(struct Stack *top)
{
if(top!=NULL)
return 1;
else
return 0;
}
int main(void)
{
struct Stack *top=NULL;
int i=0,y,flag=0;
char str[]="((A+B)+(C+D)>",op;
printf("\n Running the programe to check if the string is balanced or not ");
for(i=0;str[i]!='\0';++i)
{
if( str[i] == '(' || str[i] == '[' || str[i] == '{' || str[i] == '<' )
push(&top,str[i]);
else if( str[i] == ')' || str[i] == ']' || str[i] == '}' || str[i] == '>')
{
y=pop(&top,str[i]);
if(!y)
{
printf("\n Unbalanced Expression ");
flag=1;
}
}
}
if(!flag)
{
if(isNotEmpty(top))
printf(" \nUnbalanced Expression ");
else
printf(" \n Balanced Expression ");
}
printf("\n");
return 0;
}
Check this code it is super easy and easy to understand
package com.codewithsouma.stack;
import java.util.Arrays;
import java.util.List;
import java.util.Stack;
public class Expression {
private final List<Character> leftBrackets = Arrays.asList('(','{','[','<');
private final List<Character> rightBrackets = Arrays.asList(')','}',']','>');
public boolean isBalanced(String input) {
Stack<Character> stack = new Stack<>();
for (char ch : input.toCharArray()) {
if (isLeftBracket(ch))
stack.push(ch);
if (isRightBracket(ch)) {
if (stack.isEmpty()) return false;
char top = stack.pop();
if (!bracketsMatch(top,ch)) return false;
}
}
return stack.isEmpty();
}
private boolean isRightBracket(char ch) {
return rightBrackets.contains(ch);
}
private boolean isLeftBracket(char ch) {
return leftBrackets.contains(ch);
}
public boolean bracketsMatch(char left, char right){
return leftBrackets.indexOf(left) == rightBrackets.indexOf(right);
}
}
At first, we create a hash table and store all brackets, left brackets are key and the value is its corresponding right brackets. Then we take an expression string from the user and create a character array. then we iterate the array and take a character then we check is this character left brackets or not if it is left bracket then we put into the stack (leftBracketContainer) otherwise we check is it the right bracket if right bracket then we pop the left bracket from the stack and find the closing bracket/ opposite bracket from the hash table and matching the current character/bracket if not matched ( for example our stack contain { this bracket so its closing bracket is } we find from the hash map and our current character = ] current character != opposite bracket ) return false otherwise we continue. At last when loop over then stack should empty. (if stack contain one more left bracket that means our expression needs another right bracket) if stack empty that means our expression is balanced otherwise not.
N:B when we check left bracket or not using isItLeftBracket(ch) then we check is our map contains the keys because all keys are left brackets like the ways we cheak right bracket by using isItRightBracket(ch) here we chake our map contains the value because all the value of the map are right bracket
package com.codewithsouma.stack;
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
public class BalancedExpressionUsingMap {
private final Map<Character,Character> map;
public BalancedExpressionUsingMap() {
this.map = new HashMap<>();
map.put('(',')');
map.put('[',']');
map.put('<','>');
map.put('{','}');
}
public boolean isBalanced(String expression){
Stack<Character> leftBracketContainer = new Stack<>();
char [] arrayOfCharacter = expression.toCharArray();
for (char ch : arrayOfCharacter) {
if(isItLeftBracket(ch))
leftBracketContainer.push(ch);
else if(isItRightBracket(ch)){
if(leftBracketContainer.isEmpty()) return false;
char leftBracket = leftBracketContainer.pop();
char oppositeBracket = getOppositeBracket(leftBracket);
if (oppositeBracket != ch) return false;
}
}
return leftBracketContainer.isEmpty();
}
private char getOppositeBracket(char leftBracket) {
return map.get(leftBracket);
}
private boolean isItRightBracket(char ch) {
return map.containsValue(ch);
}
private boolean isItLeftBracket(char ch) {
return map.containsKey(ch);
}
}
Instead of allocating a stack for the delimiters, you can use a recursive function that skips balanced subexpressions and returns NULL upon mismatches:
#include <stdio.h>
const char *check(const char *s, char open) {
while (*s) {
switch (*s++) {
case ')': return (open == '(') ? s : NULL;
case ']': return (open == '[') ? s : NULL;
case '}': return (open == '{') ? s : NULL;
case '>': return (open == '<') ? s : NULL;
case '(':
case '[':
case '{':
case '<':
s = check(s, s[-1]);
if (s == NULL)
return NULL;
break;
}
}
if (open) {
/* closing delimiter not found */
return NULL;
}
return s;
}
void test(const char *s) {
printf("%s -> %s\n", s, check(s, 0) ? "Balanced" : "Unbalanced");
}
int main() {
test("((A+B)+(C+D))");
test("((A+B))+(C+D))");
test("((A+B)+(C+D)");
test("((A+B)+(C+D})");
return 0;
}
Output:
((A+B)+(C+D)) -> Balanced
((A+B))+(C+D)) -> Unbalanced
((A+B)+(C+D) -> Unbalanced
((A+B)+(C+D}) -> Unbalanced
Note that contrary to your assertion, ((A+B))+(C+D)) is unbalanced.
I am having some problems with my program and getting this error :
HEAP CORRUPTION DETECTED: before Normal block (#9873672) at 0x00968988.
CRT detected that the application wrote to memory before start of heap buffer.
I have tried to look for fixes but I can't figure out what it wrong with my program, what to fix and where :(
Here is the function I'm using and that is causing me problems :
What I am doing is basically look into a file for a specific keyword (argument of the function getText) and printing its matching value.
Sorry if most of the variables are in French, it's a project for school and our teacher require us to use French names >_<
#include "getText.h"
#include "main.h"
#include <stdlib.h>
texteLangue* ressourcesTexteLangue = NULL;
int compteur = 0;
char* getText(char* clef)
{
char* texte = NULL;
texte = clef; //clef is the keyword passed in the function as argument
texteLangue temp;
temp.clef = clef;
texteLangue* resultat = (texteLangue*) bsearch(&temp, ressourcesTexteLangue, compteur, sizeof(texteLangue), comparerClef); //returns the value associated with the key
if (clef != NULL)
{
if (resultat != NULL)
texte = resultat->valeur;
}
return texte;
}
void lectureTexte(char* langue)
{
char nomFichierRessources[64];
sprintf(nomFichierRessources, "ressources_%s.txt", langue); //give the file name a specific ending depending on the language chosen
FILE* FichierRessources = fopen(nomFichierRessources, "r");
if (FichierRessources == NULL)
{
system("cls");
perror("The following error occured ");
system("PAUSE");
exit(42);
}
//allocates memory for the language resources
int taille = 10;
ressourcesTexteLangue = (texteLangue *) calloc(taille, sizeof(texteLangue));
if (ressourcesTexteLangue == NULL)
printf("Pas assez de place mémoire pour les ressources texte");
//gives a value to TextResource.key and TextResource.value for each line of the file
char* ligne;
while ((ligne = lectureLigne(FichierRessources)))
{
if (strlen(ligne) > 0)
{
if (compteur == taille)
{
taille += 10;
ressourcesTexteLangue = (texteLangue *) realloc(ressourcesTexteLangue, taille * sizeof(texteLangue));
}
ressourcesTexteLangue[compteur].clef = ligne;
while (*ligne != '=')
{
ligne++;
}
*ligne = '\0';
ligne++;
ressourcesTexteLangue[compteur].valeur = ligne;
compteur++;
}
}
//sorts out the values of TextResource obtained
qsort(ressourcesTexteLangue, compteur, sizeof(texteLangue), comparerClef);
fclose(FichierRessources);
}
//reads a line and returns it
char* lectureLigne(FILE *fichier)
{
int longeur = 10, i = 0, c = 0;
char* ligne = (char*) calloc(longeur, sizeof(char));
if (fichier)
{
c = fgetc(fichier);
while (c != EOF)
{
if (i == longeur)
{
longeur += 10;
ligne = (char*) realloc(ligne, longeur * sizeof(char));
}
ligne[i++] = c;
c = fgetc(fichier);
if ((c == '\n') || (c == '\r'))
break;
}
ligne[i] = '\0';
while ((c == '\n') || (c == '\r'))
c = fgetc(fichier);
if (c != EOF)
ungetc(c,fichier);
if ((strlen(ligne) == 0) && (c == EOF))
{
free(ligne);
ligne = NULL;
}
}
return ligne;
}
//frees the TextRessources
void libererTexte()
{
if (ressourcesTexteLangue != NULL)
{
while (compteur--)
{
free(ressourcesTexteLangue[compteur].clef);
}
free(ressourcesTexteLangue);
}
}
//compares the keys
int comparerClef(const void* e1, const void* e2)
{
return strcmp(((texteLangue*) e1)->clef, ((texteLangue*) e2)->clef);
}
the structure of RessourceTextelangue (TextResources) look like this :
typedef struct texteLangue {
char* clef;
char* valeur;
} texteLangue;
There are several potential problems with your code that could be causing the error report you see.
Here is one:
if (i == longeur)
should be:
if ((i+1) == longeur)
otherwise,
ligne[i] = '\0';
can occur in conditions when
ligne[i++] = c;
has caused i to become equal to longeur.
Here is another:
while (*ligne != '=')
{
ligne++;
}
*ligne = '\0';
the above code should be:
while (*ligne != '=' && *ligne != '\0')
{
ligne++;
}
*ligne = '\0';
otherwise, you will corrupt memory in the case when there is no '=' to be found in the string.
Although either of these could cause the symptom you report, I see some other oddities that make me think there is more wrong than I have seen so far. Nevertheless, fixing those two problems will at least reduce the number of possibilities you have to consider.
Is your input guaranteed to contain a '=' in each line?
while (*ligne != '=') // if not, this will fly off the end of your buffer...
{
ligne++;
}
*ligne = '\0'; // ...and write to unallocated heap memory
Edit
Given #Heath's comment, if your input contains a blank line (including ending with a single blank line) then the above would most certainly be triggered.
c = fgetc(fichier); // reads '\n'
while (c != EOF)
{
...
ligne[i++] = c;
...
ligne[i] = '\0';
ligne now contains "\n" and is returned. later it is used:
if (strlen(ligne) > 0) // strlen("\n") is greater than 0
{
...
while (*ligne != '=') // oops! loop until we find a '=' somewhere
// in the heap or crash trying.
{
ligne++;
}
*ligne = '\0'; // corrupt the heap here
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;
}
this line may skip 1 or 2 or 3 characters from the input line:
nextChar(s) == '(') || (nextChar(s) == '{') || (nextChar(s) == '['
you should most definitely use:
char ch = nextChar(s);
if( ch == '(' || ch == '{' || c == '[' )
You don't seem to be incrementing s anywhere. What does your nextChar function do? I can only guess, but it seems like it'll just return *s. If that's the case, you need to increment s (++s) after each iteration. If it does magically (because there really isn't a sensible way to do that in plain C) increment s anyways, you should only call it once per iteration and save the result. I'd guess it's the former, in which case for example for this string: "(())" you will read the first '(' twice and return 0.
Update: Yeah, apparently your nextChar function does use a global counter. Advice two applies, only call it once per iteration. Or better yet, get rid of that thing. The way that function is designed, you can effectively use it exactly once in the entire lifetime of your program, and the entire functionality of that thing can be replaced by (*s ? *(s++) : *s). Or just *(s++) (and just do the check for 0 yourself).