Click here to Skip to main content
15,891,136 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
How to make a C program that checks the correctness of another program, limited to opening and closing of '{', '(', '[' .

What I have tried:

i guess need to use stack ? getting no idea of the same.
Posted
Updated 19-Nov-18 21:44pm

The simplest way is to create your own stack, and parse the data. Your stack is simply an array and an index which says "next free location"
Look at each character as you remove it from the data, and:
If it is a opening bracket, add it to your stack then increment the index.
If it's a closing bracket, remove the item at the top of the stack (by reducing the index and looking at the item on it) and check it's the same type: '(' for ')', '{' for '}' and so on.
Otherwise, ignore it.
When you get to the end of the data, if the index is zero, then any brackets in the input match up.

The advanced version might allow for brackets within C strings and character definitions
"The close bracket character is ')' while the open bracket is '('."
for example. I don't know if that is required for your homework though!
 
Share this answer
 
If you don't have to care about the pre-processor or comments then the job is rather easy. Opening a brace, parenthesis, or bracket is just looking for the occurrence of the character. Closing one of them is essentially the same, although using a different character, with the caveat that it must be open first. If not then it is incorrect. Also, any of those left open at the end of the file are incorrect also. In a real parser, yes, a stack would be used for this but for your purpose it can be much simpler. All you need are counters three counters. Start the counters at zero, increment when an opening character is found, and decrement them when the corresponding closing character is found. Start by opening the file in text mode, fopen can do this. Then read single characters at a time and evaluate each one as noted above. The function fread can do this. Remember to call fclose when the end of the file is reached.
 
Share this answer
 
Comments
OriginalGriff 20-Nov-18 3:24am    
char x[10;
if }x(0] == 'x'(
[
i++
)
]
Valid! :laugh:
You can use a linked list with a new element with type information for ever opening element and removing it for every closing element. A double linked list should be better.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900