Please explain why ?

S

Sanjeev

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",len);
}
////////////////////////////////////////////////
 
A

Allan Bruce

Sanjeev said:
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",len);
}
////////////////////////////////////////////////

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
 
V

Victor Bazarov

Allan Bruce said:
Sanjeev said:
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",len);
}
////////////////////////////////////////////////

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

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

Victor
 
A

Aggro

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

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 )
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,051
Latest member
CarleyMcCr

Latest Threads

Top