I found several answers to this in C++ or C#, but none for C.
I need to know how to count the number of characters in a string. The goal is to determine whether there is a closed block (bounded by braces '{', '}') in a string. right now I have the following:
int closedBlock(char* value) {
int open = 0;
int i;
for (i = 0; i < strlen(value); i++) {
if (!strcmp("{", value[i])) {
open++;
} else if (!strcmp("}", value[i])) {
open--;
}
}
return !open;
}
but it crashes after on the first if check. I’m not really clear on why this does not work. I imagine it has something to do with bad pointers (that seems to always be the problem in C), but I can’t figure it out. In addition to working code, and explanation of why mine is bad would be greatly helpful.
Thanks.
NOTE
I am aware that this simply check that the number of '{' is equal to the number of '}', and not truly that there is a properly closed block. I’ll solve that problem after I solve this one.
strcmpwill compare two null-terminated strings. It still baffles me that your compiler actually doesn’t mutter about the second parameter being achar. If you want to compare a single character just use the equal-operator==:Hint: If you work with
gccadd-Wall -Wextrato your compiler call, it will often result in useful warnings.Another hint here: when can there be an invalid block? If and only if the end-token
}occurs without a preceding start-token{. You already have all tools for this, you’re just missing anotherif-statement.