Maximum character frequency per line

#include<bits/stdc++.h>
#include<cstring>
#define arraySize 10

using namespace std;
char returnMaxOccur(char *str);

int main()
{
    char str[]="teet";
    cout<<"The max occuring character is"<<" "<<returnMaxOccur(str)<<endl;
    return 0;
}

char returnMaxOccur(char* str)
{
    int high=-1;
    char t;
    int counter[arraySize]={0};

    int len=strlen(str);

    for(int i=0;i<len;i++)
    {
        counter[str[i]]++;
    }


    for(int i=0;i<len;i++)
    {
        if(high<counter[str[i]])
        {
            high=counter[str[i]];
            t=str[i];
        }
    }
    return t;
}

In the next question, when the #include<bits/stdc++.h> results for the input string are included, the following:

1)teet: ans is t  
2)eett: ans is e  
3)ttee: ans is t  
4)ette: ans is e  

but when I turn on the results #include<iostream> instead#include<bits/stdc++.h>

1)teet: ans is e  
2)eett: ans is t  
3)ttee: ans is t  
4)ette: ans is e  

What is the reason for this behavior, or am I doing something wrong?

+4
source share
3 answers

This is an example tutorial on how undefined behavior can manifest itself in seemingly strange behavior.

In practice, including different headers, it is likely that they affected which bytes are at certain positions in memory, the bytes that you accidentally observe when you significantly overflow your array counter(size 10) with indexes that can go up to 255.

- std::map<char, int>, " ". , "" int[] .

(, IMO, bits/stdc++.h .)

+6

, . , :

#define arraySize 10

#define arraySize 128

as str[i] ( , ASCII- 0 127)

#include.

- - πάντα ῥεῖ ( # ?)

+1

when i=0, counter[str[i]]++- counter[116]++, but the size of the counter array is 10. Thus, the code counter[116]++changes an arbitrary memory address.

0
source

Source: https://habr.com/ru/post/1677602/


All Articles