-1

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;
}
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190

2 Answers2

7

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;
}
Géza Török
  • 1,397
  • 7
  • 15
juanchopanza
  • 223,364
  • 34
  • 402
  • 480
2

c needs a null character at the end for strlen to work.

You can use

char c[N] = {'q','t','y','t'}; 

where N is 5 or greater.

or

char c[] = {'q','t','y','t', '\0'};

or

char c[] = "qtyt";

to add a null character at the end of c.

R Sahu
  • 204,454
  • 14
  • 159
  • 270