#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 following question when #include<bits/stdc++.h>
is included the results for input string are as follows,
1)teet: ans is t
2)eett: ans is e
3)ttee: ans is t
4)ette: ans is e
but when i include #include<iostream>
instead of #include<bits/stdc++.h>
the results are
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 behaviour,or am i doing anything wrong?
This is a textbook case of how undefined behaviour can manifest in seemingly bizarre behaviour.
In practice, including different headers has likely affected what bytes are at certain positions in memory, bytes that you accidentally observe when you vastly overrun your array counter
(size 10) with indexes that could go all the way up to 255.
The traditional way to approach this task is with a std::map<char, int>
, which can effectively function as a "sparse array". Failing that, just make sure you have enough "slots" in your int[]
for every possible input.
(And, IMO, you shouldn't be using bits/stdc++.h
anyway.)
The first important thing is that your code is not correct. Please correct it as follows:
Instead of
#define arraySize 10
use
#define arraySize 128
as str[i]
may be arbitrary character (I suppose an ASCII character from 0
to 127
)
and only then repeat your testing with changing the #include
statement.
The second - and generally more important - was just expressed by πάντα ῥεῖ in his link (Why should I not #include ?)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With