473,624 Members | 2,185 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Character array Initialization

Hi,

I have question about character array initialization. In section 6.7.8
paragraph number 21, it's given that

"If there are fewer initializers in a brace-enclosed list than there
are elements or members of an aggregate, or fewer characters in a
string literal used to initialize an array of known size than there are
elements in the array, the remainder of the aggregate shall be
initialized implicitly the same as objects that have static storage
duration."

My question is that, if I declare

char sTemp[5] = "";

Is it GUARANTEED that all the five elements of the array will be
initialized to '\0'? Or is it only guarantees that that sTemp[0] will
be initialized to '\0'?

Any help greatly appreciated.

Thank you for your time.

-Kannan

Sep 9 '06 #1
6 34766
"Kannan" <ri*******@gmai l.comwrites:
Hi,

I have question about character array initialization. In section 6.7.8
paragraph number 21, it's given that

"If there are fewer initializers in a brace-enclosed list than there
are elements or members of an aggregate, or fewer characters in a
string literal used to initialize an array of known size than there are
elements in the array, the remainder of the aggregate shall be
initialized implicitly the same as objects that have static storage
duration."

My question is that, if I declare

char sTemp[5] = "";

Is it GUARANTEED that all the five elements of the array will be
initialized to '\0'? Or is it only guarantees that that sTemp[0] will
be initialized to '\0'?
It certainly looks like it's guaranteed. The paragraph you quoted
refers specifically to astring literal used to initialize an array of
known size.

Why would you suspect that it isn't guaranteed?

--
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.
Sep 9 '06 #2
Hello Kannan:

Sorry to add another question to yours... (see below)

Kannan wrote:
Hi,

I have question about character array initialization. In section 6.7.8
paragraph number 21, it's given that

"If there are fewer initializers in a brace-enclosed list than there
are elements or members of an aggregate, or fewer characters in a
string literal used to initialize an array of known size than there are
elements in the array, the remainder of the aggregate shall be
initialized implicitly the same as objects that have static storage
duration."
Does anybody know if the standard behavior is scope-specific? To
further clarify, is it portable to assume this:

/* Begin Program */
char Extern_sTemp[5] = ""; // all elements are null right?
static char Static_sTemp[5] = ""; // ditto?

int main( void )
{
char Auto_sTemp[5] = ""; // same here?
return 0;
}
/* End Program */
>
My question is that, if I declare

char sTemp[5] = "";

Is it GUARANTEED that all the five elements of the array will be
initialized to '\0'? Or is it only guarantees that that sTemp[0] will
be initialized to '\0'?
For lack of a copy of the C standard (yes I should buy it) I have coded
around this problem in my production code by using memset() or the like
to initialize the appropriate memory to a "known" default value (like
'\0', or 0, or NULL) -- whichever you prefer). Usually it would look
like this:

#define STEMP_MAXSIZE 5
....
char sTemp[ STEMP_MAXSIZE ];
memset( sTemp, 0, STEMP_MAXSIZE); // my preferred way of doing it
....

/* OR */

char sTemp[5];
memset( sTemp, 0, sizeof(sTemp) ); // I like this version less

Any help greatly appreciated.

Thank you for your time.

-Kannan
I really like the interesting point you bring up. I have looked for a
way of using memset() less to initialize contiguous areas of memory.

Below is a link to an article describing how such a simple use of
memset() can get ugly:

"Security Enhancements" (note: this article has a C++ bias)
http://www.informit.com/guides/conte...eqNum=202&rl=1

-Randall
Sr. Software Engineer
Lockheed Martin

Sep 9 '06 #3
Randall wrote:
Does anybody know if the standard behavior is scope-specific? To
further clarify, is it portable to assume this:

/* Begin Program */
char Extern_sTemp[5] = ""; // all elements are null right?
All 5 elements have value zero. They are null characters.
static char Static_sTemp[5] = ""; // ditto?
Yes, initialised to exactly the same values.
int main( void )
{
char Auto_sTemp[5] = ""; // same here?
Yes, initialised to exactly the same values.
return 0;
}
/* End Program */
If there is an initialiser present, then the initialiser has the same
meaning no matter what the scope, storage type and linkage type.

If there is no initialiser, then the behaviour depends on the storage
type. Objects with static storage (including extern and static linkage,
and in any scope) are initialised to zeros, but objects with automatic
storage are not initialised and have indeterminate values.

char ExternLinkage_S taticStorage_Fi leScope[5];

static char NoLinkage_Stati cStorage_FileSc ope[5];

void foo(void)
{
static char NoLinkage_Stati cStorage_BlockS cope[5];

char NoLinkage_Autom aticStorage_Blo ckScope[5];
}

Of these four definitions, the first three all have static storage, and
so they are automatically initialised to zeros. The last one has
automatic storage, and so it is not automatically initialised.

--
Simon.
Sep 9 '06 #4
Randall wrote:
<snipped>
#define STEMP_MAXSIZE 5
....
char sTemp[ STEMP_MAXSIZE ];
memset( sTemp, 0, STEMP_MAXSIZE); // my preferred way of doing it
....

/* OR */

char sTemp[5];
memset( sTemp, 0, sizeof(sTemp) ); // I like this version less

Your preferred way is prone to bugs when the
inevitable maintenance comes around 5 years
after you left the organisation.

My preferred way is:
memset (sTemp, 0, sizeof sTemp);

Using sizeof with unnecessary parentheses tends
to either tell the maintenance programmer that
sTemp is a typedef *OR* tell the beginner programmer
that sizeof is a function call.

But hey, different strokes ...

<snipped>

--
goose
Have I offended you? Send flames to root@localhost
real email: lelanthran at gmail dot com
website : www.lelanthran.com
Sep 9 '06 #5
Randall wrote:

[snip]
For lack of a copy of the C standard (yes I should buy it)
Or you can download the free post-Standard draft which is essentially
the C99 Standard plus TC1 and TC2:
<www.open-std.org/JTC1/SC22/WG14/www/docs/n1124.pdf>

Robert Gamble

Sep 9 '06 #6

Keith Thompson wrote:
"Kannan" <ri*******@gmai l.comwrites:

Is it GUARANTEED that all the five elements of the array will be
initialized to '\0'? Or is it only guarantees that that sTemp[0] will
be initialized to '\0'?

It certainly looks like it's guaranteed. The paragraph you quoted
refers specifically to astring literal used to initialize an array of
known size.

Why would you suspect that it isn't guaranteed?
Hmm , this actually does come as a big surprise to me. And since you
asked, the reason is that it seems to be an unnecessary waste of
runtime. If for some bizarre reason I insist on having the whole array
of chars be zerod after the initializer, I can say so; far more often,
I couldn't care less what defaults come in the places beyond an initial
terminator. In the overwhelming majority of cases, one will not be
peeking ahead of the terminator in a string.

Sep 9 '06 #7

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

Similar topics

2
10544
by: Kris | last post by:
Hi All, I just tried to do something that I thought would be quite simple in C++ and discovered (I think) that it's not possible. I did a bunch of reading and everything that I've seen seems to indicate that it's not possible but I thought I'd throw it out to all you c++ gurus to see what you say. Is there any way to initialize a character array in the initialization list for the constructor a class? If this is not possible, can anyone...
19
4541
by: Henry | last post by:
I finally thought I had an understanding of multi dimensional arrays in C when I get this: #include <stdio.h> #define max_x 3 #define max_y 5 int array;
9
3350
by: Christian Kandeler | last post by:
Hi, if I want to store the string "123456" in a variable of type char, I can do it like this: char s = "123456"; Or like this: char s = { '1', '2', '3', '4', '5', '6', '\0' };
4
9682
by: Stephen Mayes | last post by:
I have initialized an array like this. const char matrix = { {0, 1, 2, 3}, {0, 1, 2}, {0, 1} }; gcc, (with no options set,) errors unless I specify
5
24307
by: toton | last post by:
Hi, I can initialize an array of class with a specific class as, class Test{ public: Test(int){} }; Test x = {Test(3),Test(6)}; using array initialization list. (Note Test do NOT have a default ctor). Is it possible to do so in the class parameter initialization using specific ctor?
14
4066
by: Shhnwz.a | last post by:
Hi, I am in confusion regarding jargons. When it is technically correct to say.. String or Character Array.in c. just give me your perspectives in this issue. Thanx in Advance.
6
3171
by: Spiro Trikaliotis | last post by:
Hello, in a project, I stumbled upon code like follows (incomplete): #if defined(MINIXVMD) || defined(MINIX_SUPPORT) || defined(__VBCC__) || (defined(__BEOS__) && defined(WORDS_BIGENDIAN)) || define d(WATCOM_COMPILE) void *array; array=&asm6502; array=&asmz80;
2
10123
by: overdrigzed | last post by:
Hello! I wanted to get the full contents of a character array stored in a struct, i.e. _fields_ = however, ctypes seems to try to return struct.array as a Python string rather than a character array, and stops as soon as it encounters a null within the character array. I ended up having to define a dummy struct
9
11179
by: Rohit | last post by:
I am trying to initialize an array whose initializers depend on value of Enums. I take enum and then decide the initializer value, so that even if enum value changes because of addition to list even then I should be able to get correct value for the array element. I need value and state to be present in a single byte thats why I use macros. Here is what my code look like: typedef enum
0
8234
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
8172
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
8620
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
8335
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,...
1
6110
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
5563
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
4174
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1784
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1482
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.