Please explain why ?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Sanjeev

    Please explain why ?

    Output of followin program at Turbo C++ 3.0 is 7 ( Not 2 or 3).

    Please explain why ?

    ////////////////////////////////////////////////
    #include<stdio. h>
    #include<string .h>

    void main()
    {
    char ch[]={'a','b'};

    int len;
    len=strlen(ch);

    printf("%d\n",l en);
    }
    ////////////////////////////////////////////////
  • Allan Bruce

    #2
    Re: Please explain why ?


    "Sanjeev" <sanjeev_magoo@ yahoo.com> wrote in message
    news:ac6d1213.0 307231249.780ee 00a@posting.goo gle.com...[color=blue]
    > Output of followin program at Turbo C++ 3.0 is 7 ( Not 2 or 3).
    >
    > Please explain why ?
    >
    > ////////////////////////////////////////////////
    > #include<stdio. h>
    > #include<string .h>
    >
    > void main()
    > {
    > char ch[]={'a','b'};
    >
    > int len;
    > len=strlen(ch);
    >
    > printf("%d\n",l en);
    > }
    > ////////////////////////////////////////////////[/color]

    This is actually undefined, since ch is an array of chars but is not null
    terminated, if you had
    char ch[] = "ab";
    or
    char ch[] = {'a','b','\0'};
    then this would be fine and you would get your expected result
    Allan


    Comment

    • Victor Bazarov

      #3
      Re: Please explain why ?

      "Allan Bruce" <allanmb@TAKEAW AYf2s.com> wrote...[color=blue]
      >
      > "Sanjeev" <sanjeev_magoo@ yahoo.com> wrote in message
      > news:ac6d1213.0 307231249.780ee 00a@posting.goo gle.com...[color=green]
      > > Output of followin program at Turbo C++ 3.0 is 7 ( Not 2 or 3).
      > >
      > > Please explain why ?
      > >
      > > ////////////////////////////////////////////////
      > > #include<stdio. h>
      > > #include<string .h>
      > >
      > > void main()
      > > {
      > > char ch[]={'a','b'};
      > >
      > > int len;
      > > len=strlen(ch);
      > >
      > > printf("%d\n",l en);
      > > }
      > > ////////////////////////////////////////////////[/color]
      >
      > This is actually undefined, since ch is an array of chars but is not null
      > terminated, if you had
      > char ch[] = "ab";
      > or
      > char ch[] = {'a','b','\0'};
      > then this would be fine and you would get your expected result
      > Allan[/color]

      Absolutely! Another reason why it's undefined is because the 'main'
      function does not return 'int' (as it's supposed to).

      Victor


      Comment

      • Aggro

        #4
        Re: Please explain why ?

        Sanjeev wrote:
        [color=blue]
        > Output of followin program at Turbo C++ 3.0 is 7 ( Not 2 or 3).[/color]

        You have posted this guestion to C++ and C groups. Please deside what
        language you are learning. Is it C or is it C++? ( They are not the same
        language )

        Comment

        Working...