I’m new to C, and I’m working on my own explode like function. I’m trying to count how many times a specified character occurs in a string.
int count_chars(char * string, char * chr)
{
int count = 0;
int i;
for (i = 0; i < sizeof(string); i++)
{
if (string[i] == chr)
{
count++;
}
}
return count;
}
It just returns 0 every time. Can anyone explain why, please? 🙂
Your code is hopelessly flawed. Here’s how it should look like:
See this code run on example input.
Here’s what you are doing wrong:
char*), This has implications later (see #3).sizeof(string)does not give you the length of the string. It gives the size (in bytes) of a pointer in your architecture, which is a constant number (e.g. 4 on 32-bit systems).chrpoints to. This is comparing apples and oranges, and will always returnfalse, so theifwill never succeed.string[i]) to the second parameter of the function (this is the reason why that one is also achar).A “better” version of the above
Commenters below have correctly identified portions of the original answer which are not the usual way to do things in C, can result in slow code, and possibly in bugs under (admittedly extraordinary) circumstances.
Since I believe that “the” correct implementation of
count_charsis probably too involved for someone who is making their first steps in C, I ‘ll just append it here and leave the initial answer almost intact.Note: I have intentionally written the loop this way to make the point that at some stage you have to draw the line between what is possible and what is preferable.
See this code run on example input.