473,657 Members | 2,376 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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);
}
////////////////////////////////////////////////
Nov 13 '05 #1
12 3064
sa***********@y ahoo.com (Sanjeev) wrote in
news:ac******** *************** ***@posting.goo gle.com:
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'}; <--- NO terminating NULL!

int len;
len=strlen(ch);
ch[] is an array of two chars, not a C string.
printf("%d\n",l en);
}
////////////////////////////////////////////////


Thus, strlen() will run until it encounters a NULL somewhere in memory
after the memory location of ch[1].

Fix: either treat ch[] like a string or don't use string functions on it.
E.g.

char ch[] = { 'a', 'b', '\0' };

or

char ch[SOME_SIZE];

strncpy(ch, "ab", sizeof ch);

--
- Mark ->
--
Nov 13 '05 #2
Sanjeev <sa***********@ yahoo.com> scribbled the following:
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()
Insert complaint about void main() here. I'm too tired.
{
char ch[]={'a','b'}; int len;
len=strlen(ch);
Bang. You're dead. ch is not a string. It's an array of char, but
not a null-terminated one. You've just invoked undefined behaviour.
printf("%d\n",l en);
}
////////////////////////////////////////////////


The output might be anything your compiler decides, because you've let
strlen() wander all of to memory you don't even own.

--
/-- Joona Palaste (pa*****@cc.hel sinki.fi) ---------------------------\
| Kingpriest of "The Flying Lemon Tree" G++ FR FW+ M- #108 D+ ADA N+++|
| http://www.helsinki.fi/~palaste W++ B OP+ |
\----------------------------------------- Finland rules! ------------/
"The large yellow ships hung in the sky in exactly the same way that bricks
don't."
- Douglas Adams
Nov 13 '05 #3
On 23 Jul 2003 13:50:13 -0700, sa***********@y ahoo.com (Sanjeev) wrote:
Output of followin program at Turbo C++ 3.0 is 7 ( Not 2 or 3).
The output is undefined and can be anything.
Please explain why ?
The string you pass to strlen is not zero-terminated.

If you want a zero-terminated string use
char ch[] = "ab";
or
char ch[] = { 'a', 'b', '\0' };

////////////////////////////////////////////////
#include<stdio .h>
#include<strin g.h>

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

int len;
len=strlen(ch);

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


Nov 13 '05 #4
Sanjeev <sa***********@ yahoo.com> wrote:
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);
}
////////////////////////////////////////////////


oops. ch is not a string...just an array of two characters.

Most likely what happened is that once strlen went past the end of your
array, it was another 5 characters before a value of zero was found.
--
== Eric Gorr ========= http://www.ericgorr.net ========= ICQ:9293199 ===
"Therefore the considerations of the intelligent always include both
benefit and harm." - Sun Tzu
== Insults, like violence, are the last refuge of the incompetent... ===
Nov 13 '05 #5
On 23 Jul 2003 13:50:13 -0700, in comp.lang.c ,
sa***********@y ahoo.com (Sanjeev) wrote:
Output of followin program at Turbo C++ 3.0 is 7 ( Not 2 or 3).


You're a lucky boy. It could have printed 45667687798 or "memory
access violation, core dumped" or "hoo, its hedgehog season. lets
paint a moonrock loud".

Strlen counts chars till it finds a \0. Your array doesn't have room
for a \0, so strlen will keep going, wandering into memory that your
program doesn't own, until it finds such a character.

This might take forever, or your computer might not let you examine
memory you don't own, and might then warn you, or crash, or emit
nonsense.
--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.angelfire.c om/ms3/bchambless0/welcome_to_clc. html>
----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==----
http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups
---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =---
Nov 13 '05 #6
sa***********@y ahoo.com (Sanjeev) wrote (23 Jul 2003) in
news:ac******** *************** ***@posting.goo gle.com / comp.lang.c:
Output of followin program at Turbo C++ 3.0 is 7 ( Not 2 or 3).

Please explain why ?
Because it makes no sense to apply strlen to char ch[]={'a','b'}; which is not a string at all.

Nor does it make sense to ask why any program does what it does after
your illegal use of void main()


--
Martin Ambuhl
Returning soon to the
Fourth Largest City in America
Nov 13 '05 #7
In article <ac************ **************@ posting.google. com>,
sa***********@y ahoo.com (Sanjeev) wrote:
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() ***********

Using "void main ()" instead of "int main ()" produces undefined
behavior and marks you as clueless. Avoid doing this. If you had a
teacher telling you to use void main () ask him to post on comp.lang.c
and we will rip his head off.
{
char ch[]={'a','b'};

int len;
len=strlen(ch);
strlen () expects a string. Find out what the format of a string is. ch
[] is _not_ a string. Once you know what the format of a string is, it
will be obvious why ch is not a string.
printf("%d\n",l en);
}
////////////////////////////////////////////////

Nov 13 '05 #8

"Sanjeev" <sa***********@ yahoo.com> wrote in message
news:ac******** *************** ***@posting.goo gle.com...
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()


Read the FAQ 11.12 to 11.15
http://www.eskimo.com/~scs/C-faq/top.html


Nov 13 '05 #9
In <ac************ **************@ posting.google. com> sa***********@y ahoo.com (Sanjeev) writes:
Output of followin program at Turbo C++ 3.0 is 7 ( Not 2 or 3).

Please explain why ?
Please explain why you expect 2 or 3.
#include<stdio .h>
#include<strin g.h>

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

int len;
len=strlen(ch);

printf("%d\n",l en);
}


Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 13 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
3531
by: DD | last post by:
Hello, Could anyone please help me?? Is there somebody who could explain me how to make a connection to a access database with a python cgi script. I would like to use common sql commands in my python scripts as I can with MySQLdb. But I cannot even connect to the access database (see below). Could anyone explain it to me as simple as possible please. I'm using Windows XP, ActivePython 2.3.2 build 230 and Microsoft access(XP?)
3
3177
by: VijayShankar | last post by:
Can u be more specific on your question Anyway its not like Session variables are available for sometime and not available for sometime. When your session starts it is very much available unless your session ends One more thing Session variables can very much be used in Application events
1
4502
by: Yash | last post by:
Hi, Can someone please explain to me what the StreamReader.DiscardBufferedData method does? The documentation says "Use DiscardBufferedData to seek to a known location in the underlying stream and then begin reading from this new point, or to read the contents of a StreamReader more than once." I am not able to understand what exactly this means.
5
3599
by: KathyB | last post by:
If someone could just explain this to me...I just don't get it! I have an aspx page where I retrieve several session variables and use xmlDocument to transform xml file with xsl file into an instruction document (not data based) - same as using an xml web control. The resulting html is on the client? but what about the server side of things? Trying to figure out how to change and save the xmlDocument. It I put a button OUTSIDE of the...
2
2203
by: garyusenet | last post by:
I could do with something similiar, can you tell me if you think this would work for me, and if there's any advantage in working with controls this way than how I currently am. At the moment i'm using the treenodes and each treenode needs a unique entry into my rich text box. After sitting at home with MSDN i've managed to get this functionality by storing a RTF string in the tag property of the treenode. On every 'before update' of the...
9
2100
by: colin.mcnulty | last post by:
Hi, I'm a SQL Server DBA, but I guess that won't buy me any friends round here huh? ;-) I've been asked to look at the SQL that's being executed on a DB2 database from a web app, specifically when the web site does XYZ, what SQL does it run on the DB2 database? Unfortunately everyone who knew about how it works has left and I've never even seen a DB2 database before today! So, I appear to be looking at an IBM DB2 Universal Database...
61
3537
by: warint | last post by:
My lecturer gave us an assignment. He has a very "mature" way of teaching in that he doesn't care whether people show up, whether they do the assignments, or whether they copy other people's work. Furthermore, he doesn't even mark the assignments, but rather gives tips and so forth when going over students' work. To test students' capabilities for the purpose of state exams and qualifications though, he actually sits down with us at a...
3
1460
by: sathishc58 | last post by:
Hi All, Here is the code which generates Segmentation Fault. Can anyone explain why the third printf fails and the first printf works? main() { char ch={"Hello"}; char *p; p=ch; printf("Character is %c\n", *p);
2
2181
by: sathishc58 | last post by:
Hi All Please explain why strlen returns() "16" as output here and explain the o/p for sizeof() as well main() { char a={'a','b','c'}; printf("strlen=%d\n", strlen(a)); printf("sizeof=%d\n", sizeof(a)); printf("%d %d", strlen(a),sizeof a);
0
8399
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8732
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8504
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8606
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6169
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5632
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4159
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2732
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1622
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.