473,785 Members | 2,607 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Reinitializing static array???

Assume I have a static array of structures the elements of which
could be any conceivable mixture of C types, pointers, arrays.
And this array is uninitialized at program startup.

If later in the program I wish to return this array to its
startup state, can this be accomplished by writing binary
zeroes to the entire memory block with memset(). E.g.,

static struct mystruct_st {
int x1;
int *x2;
double x3[10];
- - -
} myarray[20];

/* Do things with myarray */
- - -
/* Restore initial myarray */
memset(my, 0, sizeof(myarray) );

(where "- - -" indicates other valid code)

Or do the initial values of the elements depend on the
version or implementation of C?

Thanks for your help.

Regards,
Charles Sullivan



Nov 15 '05 #1
15 4901
Charles Sullivan <cw******@triad .rr.com> wrote:
static struct mystruct_st {
int x1;
int *x2;
double x3[10];
- - -
} myarray[20]; /* Do things with myarray */
- - -
/* Restore initial myarray */
memset(my, 0, sizeof(myarray) ); Or do the initial values of the elements depend on the
version or implementation of C?


Yes. Specifically, all-bits-zero is not guaranteed to be a valid
value for an int *; the value of NULL is implementation dependent,
which is presumably what you want x2 initialized to.

--
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 #2
Charles Sullivan wrote:
Assume I have a static array of structures the elements of which
could be any conceivable mixture of C types, pointers, arrays.
And this array is uninitialized at program startup.

If later in the program I wish to return this array to its
startup state, can this be accomplished by writing binary
zeroes to the entire memory block with memset().
<snip>
No, you can't, at least not portably. In particular, the all-zeroes
bitpattern is not guaranteed to initialize floating-point variables to
0.0, it is not guaranteed to be a null pointer value (or even a valid
pointer value), etc.

It is always better to explicitly initialize variables yourself, even
static ones. If you turn that into a function, you can reinitialize the
array by calling it.
Or do the initial values of the elements depend on the
version or implementation of C?

No. The initial values are all guaranteed defaults: 0 for ints, 0.0 for
doubles, null pointers for pointers, etc. The problem is, you don't know
exactly what bits are used for initialization, so memset() won't cut it.

S.
Nov 15 '05 #3


Charles Sullivan wrote On 10/03/05 13:16,:
Assume I have a static array of structures the elements of which
could be any conceivable mixture of C types, pointers, arrays.
And this array is uninitialized at program startup.

If later in the program I wish to return this array to its
startup state, can this be accomplished by writing binary
zeroes to the entire memory block with memset(). E.g.,

static struct mystruct_st {
int x1;
int *x2;
double x3[10];
- - -
} myarray[20];

/* Do things with myarray */
- - -
/* Restore initial myarray */
memset(my, 0, sizeof(myarray) );

(where "- - -" indicates other valid code)

Or do the initial values of the elements depend on the
version or implementation of C?


A static variable is never "uninitiali zed" in C. It
may lack an explicit initializer, or it may have an
initializer that omits some of its constituent elements,
but if so all those "uninitiali zed" chunks are initialized
to zeroes of appropriate types. That is, each `int' is
initialized to `0', each `unsigned int' to `0u', each
`float' to `0.0f', each pointer to `(WhateverType* )0',
and so on.

But there's a catch: C does not specify very much about
how values are represented. For the various integer types
C promises that filling an appropriately-sized (and -aligned)
region of memory with all-bits-zero produces a zero value.
However, no such guarantee is made for `float', `double',
`long double', or pointer types. It is at least possible
that all-bits-zero is not a valid representation of `0.0f',
`0.0', or `0.0L', and may not be a valid null pointer. On
many machines it happens that these things are in fact
represented as all-bits-zero -- it's so convenient -- but
the language doesn't require it, and there are (or have been)
machines that use(d) other representations .

So: Your memset will certainly work if all the things
being zapped are integers, and will probably (but not
certainly) work if there are non-integer elements involved.
If you decide to use memset() you're running a small risk;
if you'd prefer to avoid the risk, try something like:

void clear_structs(s truct mystruct_st *p, size_t n) {
const struct mystruct_st empty = { 0 };
while (n-- > 0)
*p++ = empty;
}

--
Er*********@sun .com

Nov 15 '05 #4

Many thanks Eric, Skarmander, and Christopher for clarifying my
thinking on this issue. Your responses and advice are much
appreciated.

Regards,
Charles Sullivan

Nov 15 '05 #5
Christopher Benson-Manica wrote:

Charles Sullivan <cw******@triad .rr.com> wrote:
static struct mystruct_st {
int x1;
int *x2;
double x3[10];
- - -
} myarray[20];

/* Do things with myarray */
- - -
/* Restore initial myarray */
memset(my, 0, sizeof(myarray) );

Or do the initial values of the elements depend on the
version or implementation of C?


Yes. Specifically, all-bits-zero is not guaranteed to be a valid
value for an int *; the value of NULL is implementation dependent,
which is presumably what you want x2 initialized to.


But, given the definition of myarray[], doesn't the standard guarantee
that the memory will be initialized as all-bits-zero at program startup?
(Or does it guarantee that pointers will be NULL and floats/doubles will
be 0.0?)

While all-bits-zero may not be NULL or a valid double, won't the memset()
call set myarray[] back to what it was when the program started?

The following shows all "00"s on my system, but (un?)fortunatel y, my
system has both NULL and 0.0 represented as all-bits-zero.

==========
#include <stdio.h>

static struct
{
int i;
char *pt;
double d;
}
foo[5];

int main()
{
unsigned char *pt;
int i;

printf("sizeof = %ld\n",(long)si zeof(foo));

for ( i=0, pt=(unsigned char *)foo ; i < sizeof(foo) ; i++, pt++ )
{
if ( (i%16) == 0 )
printf("\n%03x: ",i);
if ( (i%8) == 0 )
printf(" ");
printf(" %02x",*pt);
}
printf("\n");
}
==========

--
+-------------------------+--------------------+-----------------------------+
| Kenneth J. Brody | www.hvcomputer.com | |
| kenbrody/at\spamcop.net | www.fptech.com | #include <std_disclaimer .h> |
+-------------------------+--------------------+-----------------------------+
Don't e-mail me at: <mailto:Th***** ********@gmail. com>
Nov 15 '05 #6
Kenneth Brody wrote:
Christopher Benson-Manica wrote:
Charles Sullivan <cw******@triad .rr.com> wrote:

static struct mystruct_st {
int x1;
int *x2;
double x3[10];
- - -
} myarray[20];
/* Do things with myarray */
- - -
/* Restore initial myarray */
memset(my, 0, sizeof(myarray) );

Or do the initial values of the elements depend on the
version or implementation of C?


Yes. Specifically, all-bits-zero is not guaranteed to be a valid
value for an int *; the value of NULL is implementation dependent,
which is presumably what you want x2 initialized to.

But, given the definition of myarray[], doesn't the standard guarantee
that the memory will be initialized as all-bits-zero at program startup?

No.
(Or does it guarantee that pointers will be NULL and floats/doubles will
be 0.0?)
Yes.
While all-bits-zero may not be NULL or a valid double, won't the memset()
call set myarray[] back to what it was when the program started?
No.
The following shows all "00"s on my system, but (un?)fortunatel y, my
system has both NULL and 0.0 represented as all-bits-zero.

Yes. :-)

S.
Nov 15 '05 #7
Skarmander wrote:

Kenneth Brody wrote:

[...]
Yes. Specifically, all-bits-zero is not guaranteed to be a valid
value for an int *; the value of NULL is implementation dependent,
which is presumably what you want x2 initialized to.

But, given the definition of myarray[], doesn't the standard guarantee
that the memory will be initialized as all-bits-zero at program startup?

No.
(Or does it guarantee that pointers will be NULL and floats/doubles will
be 0.0?)

Yes.


Well, that's what happens when I've apparently only worked on NULL and
0.0 are all-bits-zero platforms. The "uninitiali zed" global variables
are placed in a .bss (or equivalent) segment, which get initialized to
all bits zero.

Okay... Is it possible that a platform have more than one representation
of 0.0? For example, "static double d = 0.0;" could result in all-bits-
zero, but "d1 = 1.0; d2 = 1.0 ; d3 = d1-d2;" could result in some other
representation.
While all-bits-zero may not be NULL or a valid double, won't the memset()
call set myarray[] back to what it was when the program started?

No.


Given the "yes" to my parenthetical question above, the answer to this
one is obviously "no".
The following shows all "00"s on my system, but (un?)fortunatel y, my
system has both NULL and 0.0 represented as all-bits-zero.

Yes. :-)


:-)

--
+-------------------------+--------------------+-----------------------------+
| Kenneth J. Brody | www.hvcomputer.com | |
| kenbrody/at\spamcop.net | www.fptech.com | #include <std_disclaimer .h> |
+-------------------------+--------------------+-----------------------------+
Don't e-mail me at: <mailto:Th***** ********@gmail. com>
Nov 15 '05 #8
Kenneth Brody <ke******@spamc op.net> writes:
[...]
Well, that's what happens when I've apparently only worked on NULL and
0.0 are all-bits-zero platforms. The "uninitiali zed" global variables
are placed in a .bss (or equivalent) segment, which get initialized to
all bits zero.

Okay... Is it possible that a platform have more than one representation
of 0.0? For example, "static double d = 0.0;" could result in all-bits-
zero, but "d1 = 1.0; d2 = 1.0 ; d3 = d1-d2;" could result in some other
representation.


Theoretically, yes. It's common for a floating-point format to have
distinct representations for +0.0 and -0.0; whether 1.0-1.0, or any
other operation, might yield -0.0 is a question I won't try to answer.

[...]

One good way to get a "zero" value for a structure type is:

struct my_struct {
... member declarations ...
};
struct my_struct my_struct_zero = { 0 };

All members of my_struct_zero will be properly initialized to zero
values (0, '\0', 0.0, NULL), *not* necessarily to all-bits-zero. You
can then do:

struct my_struct obj = { 0 };
... play with obj ...
... Now we need to reset it to its initial value ...
obj = my_struct_zero;

--
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
Keith Thompson wrote:

<snip>
One good way to get a "zero" value for a structure type is:

struct my_struct {
... member declarations ...
};
struct my_struct my_struct_zero = { 0 };
I would suggest using
const struct my_struct_zero = { 0 };
So the compiler complains about any attempt to modify it otherwise
things very puzzling to another programmer could happen.
All members of my_struct_zero will be properly initialized to zero
values (0, '\0', 0.0, NULL), *not* necessarily to all-bits-zero. You
can then do:

struct my_struct obj = { 0 };
... play with obj ...
... Now we need to reset it to its initial value ...
obj = my_struct_zero;

--
Flash Gordon
Living in interesting times.
Although my email address says spam, it is real and I read it.
Nov 15 '05 #10

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

Similar topics

3
35295
by: Rahul Joshi | last post by:
Hi, I want to create a static array whose size is also a const member of the class. Something like: // A.h class A { private: static int size = 0; static int array;
1
2745
by: John David Ratliff | last post by:
I'm new to C++ and have a question about static class constants. Let's say we have two classes --------------------------------------------- #include <iostream> using namespace std; class Color {
7
1915
by: Eric | last post by:
My program will create a few instance of class A. Class A will always need this 256byte array that is used for bitcounting. I have a function that fills the array. How do a right a class or object that will only create one of these arrays that every class A can see?
8
4592
by: Scott J. McCaughrin | last post by:
The following program compiles fine but elicits this message from the linker: "undefined reference to VarArray::funct" and thus fails. It seems to behave as if the static data-member: VarArray::funct were an extern, but it is declared in the same file (q.v.). What is the remedy for this? =================
5
1923
by: Mountain Bikn' Guy | last post by:
How would I do this? public sealed class UtilityClass { public static MyObject Object1;//see note below about importance of static object names in this class public static MyObject Object2; // ... public static MyObject Object400;
12
24813
by: Sergey Klementiev | last post by:
Why it's impossible to have a static indexer in C#?
6
2812
by: silverburgh.meryl | last post by:
Hi, In one A.cpp file, I have defined a static array of JSFunctionSpec, like this: static JSFunctionSpec JProfFunctions = { {"JProfStartProfiling", JProfStartProfiling, 0, 0, 0 }, {"JProfStopProfiling", JProfStopProfiling,
6
2944
by: npankey | last post by:
I've started experimenting with template metaprogramming in a small project of mine. What I'm trying to accomplish is to generate a static array of templated objects that get specialized based on there position in the array. This should be possible but I can't figure out exactly how to accomplish this. The below code should better illustrate what I'm trying to do: template <int I> class Item
2
3767
by: yeshello54 | last post by:
so here is my problem...in a contact manager i am trying to complete i have ran into an error..we have lots of code because we have some from class which we can use...anyways i keep getting an error when i do the following. if you add a contact with up to 13 fields it will be stored in a data structure. i have a tabbed pane that will show six of the 13 fields for that contact. when you double click the contact i want it to pop up and show all 13...
0
9645
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
10341
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...
1
10095
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
7502
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
6741
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
5383
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...
0
5513
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3656
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2881
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.