M
M
mottoper2014-06-20 13:53:15
Programming
mottoper, 2014-06-20 13:53:15

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;
}

The function persistently returns the value 32770, where did I go wrong?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
M
mottoper, 2014-06-20
@mottoper

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.

S
Sergey, 2014-06-20
Protko @Fesor

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.

R
RPG, 2014-06-20
@RPG

To avoid running into such errors again, use the cppcheck analyzer, it will immediately issue a warning:
[test.cpp:25]: (error) Uninitialized variable: a1

J
jcmvbkbc, 2014-06-20
@jcmvbkbc

Here's another option for you:

#include <string.h>
int nullcount(const char* str)
{
    int count = 0;
    while (*str) {
        int cur = strspn(str, "0");
        if (cur > count)
            count = cur;
        str += cur + strcspn(str + cur, "0");
    }
    return count;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question