Answer the question
In order to leave comments, you need to log in
Why does the function return such a strange value?
In general, I went through a third of the initial textbook on c ++ and solve various simple problems, create a function that counts the largest number of consecutive zeros in a string. Here is the code:
#include <iostream>
using namespace std;
int nullcount(char *str);
int main()
{
int c;
char str[] = "0001001100000011";
c = nullcount(str);
cout << c;
}
int nullcount(char *str)
{
int a=0;
for(int i = 0; str[i]; i++)
{
if (str[i] == '0')
{
int a1;
for (int i1 = i; str[i1] == '0'; i1++)
{
a1++;
}
if (a1 > a)
{
a = a1;
a1 = 0;
}
}
}
return a;
}
Answer the question
In order to leave comments, you need to log in
Opa, I already figured it out, it was necessary to set the variable a1 to 0 when declaring it. How can I delete the question? Here I am an idiot, I thought for half an hour, as soon as I posted it, I immediately guessed.
What is the purpose of the inner loop? You get to count at each iteration anew, just one element less ...
In any case, the loop exit conditions are to blame.
To avoid running into such errors again, use the cppcheck analyzer, it will immediately issue a warning:[test.cpp:25]: (error) Uninitialized variable: a1
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question