473,796 Members | 2,495 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
15 4904
Flash Gordon <sp**@flash-gordon.me.uk> writes:
Keith Thompson wrote:
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.


Yes, thanks for the improvement.

--
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 #11
in comp.lang.c i read:
Assume I have a static array
[...] uninitialized at program startup.
which is to say implicitly initialized, every member of every element to
the type's zero value, whether that means all bits zero or something else.
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.,


not portably.

use a second static object, and memcpy if it's an array. if the array is
large a single element and a loop.

--
a signature
Nov 15 '05 #12

Eric Sosman wrote:
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;


why not the much simpler
*p = empty;

And there is no need for the argument 'n'

Am I missing something? BTW {0} syntax in the init may not
work in the first member in mystruct_st itself is a struct.
It may need {{0}} or even {{{0}}} (If that struct also had a struct
as first member)

Karhik

}

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


Nov 15 '05 #13

In article <11************ **********@o13g 2000cwo.googleg roups.com>, "ka*****@gmail. com" <ka*****@gmail. com> writes:

BTW {0} syntax in the init may not
work in the first member in mystruct_st itself is a struct.
It may need {{0}} or even {{{0}}} (If that struct also had a struct
as first member)


No, it need not. {0} is always a valid initializer for an object
of any complete type, or an array of unknown size. (Obviously it's
not valid for objects of incomplete type, namely incomplete structs
and unions and variable-length arrays.)

For scalar objects, {0} follows from ISO 9899-1999 6.7.8 #11. For
aggregate and union objects, {0} follows from the same section, #13,
#16, #17, and #19-#22. See also (non-normative) footnote 127.

Chapter and verse if you believe otherwise, please.

--
Michael Wojcik mi************@ microfocus.com

The lark is exclusively a Soviet bird. The lark does not like the
other countries, and lets its harmonious song be heard only over the
fields made fertile by the collective labor of the citizens of the
happy land of the Soviets. -- D. Bleiman
Nov 15 '05 #14
Michael Wojcik wrote:
In article <11************ **********@o13g 2000cwo.googleg roups.com>, "ka*****@gmail. com" <ka*****@gmail. com> writes:

BTW {0} syntax in the init may not
work in the first member in mystruct_st itself is a struct.
It may need {{0}} or even {{{0}}} (If that struct also had a struct
as first member)
No, it need not. {0} is always a valid initializer for an object
of any complete type, or an array of unknown size. (Obviously it's
not valid for objects of incomplete type, namely incomplete structs
and unions and variable-length arrays.)

For scalar objects, {0} follows from ISO 9899-1999 6.7.8 #11. For
aggregate and union objects, {0} follows from the same section, #13,
#16, #17, and #19-#22. See also (non-normative) footnote 127.

Chapter and verse if you believe otherwise, please.


You could be right since I have only seen the behavior of gcc
in such a case. As you say, probably it is very valid C. I double
checked, it is just that gcc is emitting different warnings. It does
produce correct runtime behavior though.

$>cat struct_init.c
#include <stdio.h>
#include <stdlib.h>
typedef struct foo_phy_st_ {
int age;
int ht;
int wt;
} foo_phy_st;

typedef struct foo_edu_st_ {
int years;
} foo_edu_st;
typedef struct foo_person_st_ {
foo_phy_st phy;
foo_edu_st edu;
} foo_person_st;


int main (void)
{
#ifdef MULTI_BRACES
foo_person_st a = {{0}};
#else
foo_person_st a = {0};
#endif
printf("%d %d\n", a.phy.age, a.edu.years);
return 0;
}

$> gcc -Wall -W -ansi -pedantic struct_init.c
struct_init.c: In function `main':
struct_init.c:2 5: warning: missing braces around initializer
struct_init.c:2 5: warning: (near initialization for `a.phy')
struct_init.c:2 5: warning: missing initializer
struct_init.c:2 5: warning: (near initialization for `a.phy.ht')
struct_init.c:2 5: warning: missing initializer
struct_init.c:2 5: warning: (near initialization for `a.edu')
$> gcc -Wall -W -ansi -pedantic -DMULTI_BRACES struct_init.c
struct_init.c: In function `main':
struct_init.c:2 3: warning: missing initializer
struct_init.c:2 3: warning: (near initialization for `a.phy.ht')
struct_init.c:2 3: warning: missing initializer
struct_init.c:2 3: warning: (near initialization for `a.edu')
$> gcc -ansi -pedantic struct_init.c
struct_init.c: In function `main':
struct_init.c:2 5: warning: missing braces around initializer
struct_init.c:2 5: warning: (near initialization for `a.phy')
struct_init.c:2 5: warning: missing initializer
struct_init.c:2 5: warning: (near initialization for `a.phy.ht')
struct_init.c:2 5: warning: missing initializer
struct_init.c:2 5: warning: (near initialization for `a.edu')
$> gcc struct_init.c
struct_init.c: In function `main':
struct_init.c:2 5: warning: missing braces around initializer
struct_init.c:2 5: warning: (near initialization for `a.phy')
struct_init.c:2 5: warning: missing initializer
struct_init.c:2 5: warning: (near initialization for `a.phy.ht')
struct_init.c:2 5: warning: missing initializer
struct_init.c:2 5: warning: (near initialization for `a.edu')

$> gcc -Wall -W -ansi -std=c99 -pedantic struct_init.c
struct_init.c: In function `main':
struct_init.c:2 5: warning: missing braces around initializer
struct_init.c:2 5: warning: (near initialization for `a.phy')
struct_init.c:2 5: warning: missing initializer
struct_init.c:2 5: warning: (near initialization for `a.phy.ht')
struct_init.c:2 5: warning: missing initializer
struct_init.c:2 5: warning: (near initialization for `a.edu')

$> gcc --version
gcc (GCC) 3.3.3 (Yellow Dog Linux 3.3.3-16.ydl.8)
Copyright (C) 2003 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is
NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.

Karthik
--
Michael Wojcik mi************@ microfocus.com

The lark is exclusively a Soviet bird. The lark does not like the
other countries, and lets its harmonious song be heard only over the
fields made fertile by the collective labor of the citizens of the
happy land of the Soviets. -- D. Bleiman


Nov 15 '05 #15

In article <11************ *********@g43g2 000cwa.googlegr oups.com>, "ka*****@gmail. com" <ka*****@gmail. com> writes:
Michael Wojcik wrote:
In article <11************ **********@o13g 2000cwo.googleg roups.com>, "ka*****@gmail. com" <ka*****@gmail. com> writes:

BTW {0} syntax in the init may not
work in the first member in mystruct_st itself is a struct.
It may need {{0}} or even {{{0}}} (If that struct also had a struct
as first member)


No, it need not. {0} is always a valid initializer for an object
of any complete type, or an array of unknown size.


You could be right since I have only seen the behavior of gcc
in such a case. As you say, probably it is very valid C. I double
checked, it is just that gcc is emitting different warnings.


The behavior of an implementation - even the behavior of *all*
implementations - does not define the language; the standard does.
Obviously, if commonly-used implementations deviate from the standard
in some way (which is not the case with gcc here; I'm just hypothe-
sizing), it may be practical to write for them rather than for the
language as it's actually defined. However, it's usually unwise to
make claims here that are backed up only by experimenting with a
single implementation. If you wish to do so anyway, I recommend
qualifying them ("With gcc, ...").

Of course an implementation can emit whatever diagnostics it likes,
even if it's complaining about a perfectly valid and useful
construct.

[OT] Splint also complains about {0} as an initializer in some
cases, such as when initializing an array of struct. Very annoying;
it's on my list of misfeatures to fix. (I am, on the whole, not
very fond of Splint, but it's one of the better choices among the
free tools. I may yet seek budget for switching my group to a
commercial tool for C static defect analysis, though.)

--
Michael Wojcik mi************@ microfocus.com

Push up the bottom with your finger, it will puffy and makes stand up.
-- instructions for "swan" from an origami kit
Nov 15 '05 #16

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

Similar topics

3
35296
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
1916
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
4595
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
1924
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
24816
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
2946
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
9683
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
9529
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
10457
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
10231
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...
0
9054
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5443
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
5576
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3733
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2927
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.