why this code gives the wrong output?? Output is 5 and 9, shouldn't it be 5 and 4. Here is the code
int main
{
char a[10] ={'a','b','c','d','e'};
char c[] = {'q','t','y','t'};
cout<<strlen(c)<<endl<<strlen(a);
return 0;
}
You have undefined behaviour, because you're calling strlen
with a pointer to a character array that is not null-terminated (c
). You need to pass null-terminated strings for this to work. This is an example, fixing that and some other errors, and including the required headers:
#include <iostream> // std:cout, std::endl
#include <cstring> // std::strlen
int main()
{
char a[10] ={'a','b','c','d','e'}; // OK, all remaining elements
// initialized to '\0'.
// Alternative: char a[10] = "abcde"
char c[] = {'q','t','y','t', '\0'}; // or char c[] = "qtyt";
std::cout << std::strlen(c) << std::endl;
std::cout << std::strlen(a) << std::endl;
}