473,726 Members | 2,142 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Null character and fixed strings

Hi,
Till now I do not understand how the null character automatically added
to the end of the string and it is not an element of the string array .
All books said the null character (\0) added automatically to the end
of the string.

Let say
char name[9]="123456789"
If entered the name in a loop;

for (i=0;i<9;i++)
printf("%c",nam e[i]);

printf("%c",nam e[i+1]);
will I see name[10] as \0 Null character ?

Nov 15 '05 #1
15 2145
eh**********@gm ail.com wrote:
Hi,
Till now I do not understand how the null character automatically added
to the end of the string and it is not an element of the string array .
All books said the null character (\0) added automatically to the end
of the string.

Let say
char name[9]="123456789"
If entered the name in a loop;

In this assignment the compiler copies from the
constant nul terminated string, which has elements
"123456789\ 0" to the array 'name', which has space
for 9 elements, so it stops at '9'. What you get
is not a nul terminated string, but a nine char
long array holding the characters 1 to 9.
for (i=0;i<9;i++)
printf("%c",nam e[i]);

printf("%c",nam e[i+1]);

Here you go wrong, accessing the 10th element of a
9 element array.

will I see name[10] as \0 Null character ?


Not in your example (you invoke undefined behaviour when
you access name[9], because name is only 9 in size).

When you exit the loop i==9, not 10 (assuming this
is a snippet of code and you've previously done things
like "#include <stdio.h>" and declared i). You are
accessing name[9], which is the 10th element of the
array (starting from name[0]).

To get the terminating nul copied to name either declare
it like:
char name[10] = "123456789" ;

So it is big enough to hold the terminating nul. Or:
char name[] = "123456789"

The compiler looks at the assignment and makes name
big enough to hold the entire string. "sizeof name"
will tell you how big that is.

--
imalone
Nov 15 '05 #2
What you mean that is always a must to leave en element space in the
end of an array string to copy the null character by the compiler ?
If I did not what are the consequneces ?

Nov 15 '05 #3
eh**********@gm ail.com wrote:
Hi,
Till now I do not understand how the null character automatically added
to the end of the string and it is not an element of the string array .
All books said the null character (\0) added automatically to the end
of the string.

Let say
char name[9]="123456789"
If entered the name in a loop;

for (i=0;i<9;i++)
printf("%c",nam e[i]);

printf("%c",nam e[i+1]);
will I see name[10] as \0 Null character ?


No for 2 reasons.
1) Arrays are indexed from 0 not one, so you meant name[9]
2) You *explicitly* told the compiler to only allocate space for 9
chars.

If you do
char name[] = "123456789"
the compiler will allocate space for 10 chars assuming you wanted a
string (which in C *must* be terminated by a \0) rather than an array of
chars that is not a string.

Equally, if you use a string literal somewhere other than initialising
an array the compiler will add the \0 on the end, so you can do things like:

char *name = "dummy"
....
if (strcmp(name,"f red"))

without having to explicitly add the \0 yourself.

If you did
char name[some_number_lar ger_than_9] = "123456789"
Then elements name[9] to the end of the array would be set to \0, but
that is for a different reason.
--
Flash Gordon
Living in interesting times.
Although my email address says spam, it is real and I read it.
Nov 15 '05 #4
<pertinent references reinserted, to quote from
others on this group,
"Please quote enough of the previous message for context. To do so from
Google, click "show options" and use the Reply shown in the expanded
header.">

eh**********@gm ail.com wrote:
Let say
char name[9]="123456789"
If entered the name in a loop;


Ian Malone wrote:
In this assignment the compiler copies from the
constant null terminated string, which has elements
"123456789\ 0" to the array 'name', which has space
for 9 elements, so it stops at '9'. What you get
is not a null terminated string, but a nine char
long array holding the characters 1 to 9.
eh**********@gm ail.com wrote: What you mean that is always a must to leave en element space in the
end of an array string to copy the null character by the compiler ?
If I did not what are the consequneces ?


It is not a must, but it does make sense. The consequence
in this case is that the null terminating character is not
copied. As a result what you have is an array of characters,
not a C-style null terminated array. This means most (all?)
of the standard functions for strings (such as strlen) will
not work with it. The least error prone solution is to
provide an array of unknown size to be initialized.
char name[] = "123456789"


What I'm curious about, if anyone reading knows, is what happens
when the array is not large enough to hold a character in the
initializer other than '\0'?
6.7.8 of C9X FCD:
[#2] No initializer shall attempt to provide a value for an
object not contained within the entity being initialized.

[#14] An array of character type may be initialized by a
character string literal, optionally enclosed in braces.
Successive characters of the character string literal
(including the terminating null character if there is room
or if the array is of unknown size) initialize the elements
of the array.

14 seems to make special provision for the case of the null
character alone, 2 seems to imply the general case:
char too_short[1] = "too_long";

Is undefined: am I reading that right?

--
imalone
Nov 15 '05 #5
eh**********@gm ail.com writes:
What you mean that is always a must to leave en element space in the
end of an array string to copy the null character by the compiler ?
If I did not what are the consequneces ?


One more time.

If you want to post a followup via groups.google.c om, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 15 '05 #6
I need to complete that discussion
-I still need to know when I should add the null character at the end
of the string array ?
-When the compiler add it automatically ?
-should I add a space element to the end of the array to keep for the
compiler space for that automatically addition ?

Nov 15 '05 #7
eh**********@gm ail.com wrote:
I need to complete that discussion
What discussion? Hint: Quoting relevant portions of preceding
conversations is enormously helpful.
-I still need to know when I should add the null character at the end
of the string array ?
If it isn't there, you don't have a string. Sometimes the standard
string functions take care of it for you, sometimes not. Consult your
favorite references for details.
-When the compiler add it automatically ?
const char *mystr="foo"; /* terminating null character taken care of */
char mystr[]="foo"; /* again taken care of */
char mystr[]={ 'f', 'o', 'o', '\0' }; /* must be explicit here */
-should I add a space element to the end of the array to keep for the
compiler space for that automatically addition ?


Any character array you plan to put a string in must be at least one
byte larger than the length of that string, to accomodate the null
terminating character. IOW, "yes".

--
Christopher Benson-Manica | I *should* know what I'm talking about - if I
ataru(at)cybers pace.org | don't, I need to know. Flames welcome.
Nov 15 '05 #8
Christopher Benson-Manica <at***@nospam.c yberspace.org> writes:
eh**********@gm ail.com wrote:

[...]
-When the compiler add it automatically ?


const char *mystr="foo"; /* terminating null character taken care of */
char mystr[]="foo"; /* again taken care of */
char mystr[]={ 'f', 'o', 'o', '\0' }; /* must be explicit here */


Another example:

char arr[3] = "foo"; /* special case, no terminating null character */

For this reason, it's usually better *not* to specify the size of a
char array initialized with a string literal, unless you specifically
don't want the terminating '\0' or you want the array to be bigger
than the string:

char arr[20] = "foo"; /* first 4 chars are 'f', 'o', 'o', '\0' */

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 15 '05 #9
On Thu, 20 Oct 2005 02:42:49 GMT, in comp.lang.c , Keith Thompson
<ks***@mib.or g> wrote:
char arr[20] = "foo"; /* first 4 chars are 'f', 'o', 'o', '\0' */


ICBW, but in fact isn't it the case that the first three chars are
'f','o', and 'o' and all the rest are '\0' ?
--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.ungerhu.com/jxh/clc.welcome.txt >

----== Posted via Newsfeeds.Com - Unlimited-Uncensored-Secure Usenet News==----
http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups
----= East and West-Coast Server Farms - Total Privacy via Encryption =----
Nov 15 '05 #10

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

Similar topics

7
5546
by: BlueDragon | last post by:
I don't know enough math to demonstrate that any numerical operation with a null should yield a null; although I would guess that it's true. I just don't buy it, however, when dealing with strings and nulls. In a simple table with first, middle and last name columns, I would infer that a null value in the middle name column means the HR person forgot to ask. A zero length string, however, tells me HR did ask and there is no middle name....
1
5527
by: Tajmiester | last post by:
Hi, And thanks for any help. I am having trouble declaring a struct containing strings that can be Serialized using the following functions. It works, but the strings wont store the right number of characters, they store one less with a null at the end! Whats the point in a marshalling as fixed length if it wastes space with a null! How can i make it marshall the strings as "proper" fixed length strings, where the full 8 (or 3)...
2
9238
by: Ithaqua | last post by:
How do you create them? -- Cheers Ithaqua
23
7411
by: sandy | last post by:
I need (okay, I want) to make a dynamic array of my class 'Directory', within my class Directory (Can you already smell disaster?) Each Directory can have subdirectories so I thought to put these in an array. The application compiles but aborts without giving me any useful information. What I suspect is happening is infinite recursion. Each Directory object creates an array of Subdirectories each of which has an array of...
12
1981
by: semut | last post by:
Given that the string is of null terminated type. What could be the possible causes (by experience) the string to have no null terminated and cause buffer overflow later. I know it is quite broad, just like to find out the causes as much as possible so that I could impose stricter checking toward my codes. note: I could not use std::string cause it will require a total rewrite. thanks.
3
12591
by: amija0311 | last post by:
Hi, I am new using DB2 9.1 database by windows base. I want to query the data that contain string then translate the string into integer using DB2. The problems is If the data is null, i got the problem to translate. How to translate string also allow null data to integer. If null data it will read as space. My Data :- GEOSEG_ID SEQNO
11
3654
by: coomberjones | last post by:
I have a few std::strings that I am using to store raw binary data, each of which may very well include null bytes at any point or points. I want to slap them together into a single string, so I tried a std::ostringstream: std::ostringstream oss; oss << x << y << z; std::string result ( oss.str() ); The result shows that feeding the ostringstream with a string just
7
3593
by: Keith Thompson | last post by:
"mkeles84" <mkeles84@hotmail.comwrites: comp.std.c deals with the C standard -- the document, how it's developed, and so forth. comp.lang.c deals with the C language, and that's where your question belongs. I've cross-posted there and set followups. NULL (all-caps) is a macro that expands to a null pointer constant. What you're asking about is the null character, '\0', sometimes refered to as NUL (one L).
19
2050
by: bowlderyu | last post by:
Hello, all. If a struct contains a character strings, there are two methods to define the struct, one by character array, another by character pointer. E.g, //Program for struct includeing character strings, test1.c #include <stdio.h> #define LEN 20 struct info {
0
8890
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
8752
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9402
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9120
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
6702
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
6011
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
4785
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2639
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2157
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.