473,320 Members | 1,887 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

struct initialization

Hi all,
I am new to C++ programming. Can some body explain how to intialize the
structure values, consider this program,

#include <iostream.h>
struct mystruct
{
int a,b,c,d,e,f;
};

class myclass
{
mystruct x;
public:
myclass(){}
void display(){
cout <<"Hi guys ";
}
};

int main()
{
myclass me;
me.display();

}
If you debug this program in gdb and stop it in display() and see the
values of "x" they all contain some garbage values. I know we have to
intialize the values of struct in the constructor, to over come this
problem, we have to explicitly assign values to each and every
member of your structure like this,

myclass () { x.a=0;x.b=0;x.c=0;x.d=0;x.e=0;x.f=0;} But your code will
become messy when the members of the structure you have to intialize
are huge. Is their any way I can assign zero values to all of the
members of the structure at one shot? I mean any function that can be
used on Linux to do this initialization??

Some body please explain,
Seema Rao

Jul 18 '06 #1
14 4854
seema wrote:
#include <iostream.h>
struct mystruct
{
int a,b,c,d,e,f;
};
mystruct x;
are huge. Is their any way I can assign zero values to all of the
members of the structure at one shot? I mean any function that can be
used on Linux to do this initialization??
how about memset
memset((void*)&x,0,sizeof(mystruct));

Jul 18 '06 #2

seema wrote:
Hi all,
I am new to C++ programming. Can some body explain how to intialize the
structure values, consider this program,

#include <iostream.h>
should be:
#include <iostream>
struct mystruct
{
int a,b,c,d,e,f;
};
Why not define a ctor here with an init list - change the initial
values to whatever you need:

struct MyStruct
{
int a,b,c,d,e,f;
MyStruct() : a(0), b(0), c(0), d(0), e(0), f(0) { }
~MyStruct() { }
};
>
class myclass
{
mystruct x;
public:
myclass(){}
myclass() : MyStruct() { }
~ myclass() { }
void display(){
cout <<"Hi guys ";
}
void display()
{
std::cout << "a = " << a << "\n";
std::cout << "b = " << b << "\n";
std::cout << "c = " << c << "\n";
std::cout << "d = " << d << "\n";
std::cout << "e = " << e << "\n";
std::cout << "f = " << f << std::endl;
}
};

int main()
{
myclass me;
me.display();

}
If you debug this program in gdb and stop it in display() and see the
values of "x" they all contain some garbage values. I know we have to
intialize the values of struct in the constructor, to over come this
problem, we have to explicitly assign values to each and every
member of your structure like this,

myclass () { x.a=0;x.b=0;x.c=0;x.d=0;x.e=0;x.f=0;} But your code will
become messy when the members of the structure you have to intialize
are huge. Is their any way I can assign zero values to all of the
members of the structure at one shot? I mean any function that can be
used on Linux to do this initialization??

This describes the need for default constructors. You could just as
well add parametized ctors in the examples above. You are not limited
to only provide a single ctor.
>
Some body please explain,
Seema Rao
Jul 18 '06 #3
No their is no way i can declare a constructor in the mystruct because
i mentioned
this structure just for illustration. But in real case the structure I
am using is from the
library, it's theora_info structure.
Salt_Peter wrote:
seema wrote:
Hi all,
I am new to C++ programming. Can some body explain how to intialize the
structure values, consider this program,

#include <iostream.h>

should be:
#include <iostream>
struct mystruct
{
int a,b,c,d,e,f;
};

Why not define a ctor here with an init list - change the initial
values to whatever you need:

struct MyStruct
{
int a,b,c,d,e,f;
MyStruct() : a(0), b(0), c(0), d(0), e(0), f(0) { }
~MyStruct() { }
};

class myclass
{
mystruct x;
public:
myclass(){}

myclass() : MyStruct() { }
~ myclass() { }
void display(){
cout <<"Hi guys ";
}

void display()
{
std::cout << "a = " << a << "\n";
std::cout << "b = " << b << "\n";
std::cout << "c = " << c << "\n";
std::cout << "d = " << d << "\n";
std::cout << "e = " << e << "\n";
std::cout << "f = " << f << std::endl;
}
};

int main()
{
myclass me;
me.display();

}
If you debug this program in gdb and stop it in display() and see the
values of "x" they all contain some garbage values. I know we have to
intialize the values of struct in the constructor, to over come this
problem, we have to explicitly assign values to each and every
member of your structure like this,

myclass () { x.a=0;x.b=0;x.c=0;x.d=0;x.e=0;x.f=0;} But your code will
become messy when the members of the structure you have to intialize
are huge. Is their any way I can assign zero values to all of the
members of the structure at one shot? I mean any function that can be
used on Linux to do this initialization??


This describes the need for default constructors. You could just as
well add parametized ctors in the examples above. You are not limited
to only provide a single ctor.

Some body please explain,
Seema Rao
Jul 18 '06 #4
seema wrote:
Hi all,
I am new to C++ programming. Can some body explain how to intialize the
structure values, consider this program,

#include <iostream.h>
struct mystruct
{
int a,b,c,d,e,f;
};
Unfortunately, one of the stupidest inconsistancies in C++ is
that default initialization does not always occur for PODs.
Initializingmystruct elements can be done one of three ways:

If mystruct is statically allocated, it will be default (zero)
initialized for you. Otherwise you can use the aggregate initializer:
mystruct foo = { 1,2,3,4,5,6 };

If mystruct is allocated via new, you can specifically request default
initialization:
mystruct *fp = new mystruct();
Without the parens it is left unitialized. There's no way to do other
than default initialization in this case.
If mystruct is allocated as a non-static local variable (stack) you
must aggregate initialize it explicitly if you care
mystruct foo = { 0 }; // remainder is also initialzed to 0
or as above.
>
>
myclass () { x.a=0;x.b=0;x.c=0;x.d=0;x.e=0;x.f=0;}
You could add a constructor to mystruct (but it would stop being
POD):
mystruct::mystruct() : a(0), b(0), c(0), d(0), e(0), f(0) { }

Another idea is to just assign a properly default initialized object:

myclass() {
static mystruct init; // this is default initialized
x = init;
}
Jul 18 '06 #5
voidtwerp wrote:
seema wrote:
>#include <iostream.h>
struct mystruct
{
int a,b,c,d,e,f;
};
>mystruct x;
>are huge. Is their any way I can assign zero values to all of the
members of the structure at one shot? I mean any function that can be
used on Linux to do this initialization??

how about memset
memset((void*)&x,0,sizeof(mystruct));
Memset is a lousy way of initializing pods. It will work for
ints, but if mystruct had pointers or reals in it, there's no
guarantee that writing zero bytes all over it is the same as
assigning zeros to it.
Jul 18 '06 #6
voidtwerp posted:

memset((void*)&x,0,sizeof(mystruct));

This will only work for integer types.
Anyway, there's a better way of doing it (see else-thread).
--

Frederick Gotham
Jul 18 '06 #7
seema posted:

myclass(){}


Don't resort to messy, non-portable means. The following is fully-portable
and does exactly what you want:
myclass() : x() {}

--

Frederick Gotham
Jul 18 '06 #8
Ron Natalie wrote:
seema wrote:
>Hi all,
I am new to C++ programming. Can some body explain how to intialize
the structure values, consider this program,

#include <iostream.h>
struct mystruct
{
int a,b,c,d,e,f;
};

Unfortunately, one of the stupidest inconsistancies in C++ is
that default initialization does not always occur for PODs.
I find this hypocritical, Ron. You're enjoying the speed of your C++
programs thanks to omitting the initialisations for PODs, and then keep
bitching about them. Of course, I can be wrong about the enjoyment
part...
Initializingmystruct elements can be done one of three ways:

If mystruct is statically allocated, it will be default (zero)
initialized for you.
Please don't confuse things here. Zero-initialisation of the storage
of static objects has nothing to do with "default initialisation". It
is not done because you didn't ask ("default"). It's done at the
program start for all of them independent of your actions, simply
because you made the objects static.
Otherwise you can use the aggregate
initializer: mystruct foo = { 1,2,3,4,5,6 };

If mystruct is allocated via new, you can specifically request default
initialization:
....otherwise known as "value-initialisation"...
mystruct *fp = new mystruct();
Without the parens it is left unitialized. There's no way to do
other than default initialization in this case.
Copy-initialisation is possible, but you need a prototype object for
that (or a function returning the prototype object).
If mystruct is allocated as a non-static local variable (stack) you
must aggregate initialize it explicitly if you care
mystruct foo = { 0 }; // remainder is also initialzed to 0
or as above.
Empty curly braces are also allowed, I believe. You can also
copy-initialise from a temporary:

mystruct foo = mystruct();

(which will be value-initialised in that case).
>>
myclass () { x.a=0;x.b=0;x.c=0;x.d=0;x.e=0;x.f=0;}

You could add a constructor to mystruct (but it would stop being
POD):
mystruct::mystruct() : a(0), b(0), c(0), d(0), e(0), f(0) { }

Another idea is to just assign a properly default initialized object:
"Properly" is a stretch here.
>
myclass() {
static mystruct init; // this is default initialized
The storage is actually _zero_-initialised, and no other initialisation
is performed (remember, C++ is stupidly inconsistent when it comes to
PODs?)
x = init;
}
It is actually better to have 'myclass'-wide static and _initialise_
the 'x' member by copying the 'init', instead of assigning it (FAQ):

class myclass {
static mystruct init;
mystruct x;
public:
myclass() : x(init) {}
};

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Jul 18 '06 #9
Hi

seema wrote:
No their is no way i can declare a constructor in the mystruct because
i mentioned
this structure just for illustration. But in real case the structure I
am using is from the
library, it's theora_info structure.
Well, then use the Theora API:

| void theora_info_init(theora_info * c)
| Initialize a theora_info structure.
| All values within the given theora_info structure are initialized, and
| space is allocated within libtheora for internal codec setup data.

We're drifting off-topic...

Markus

Jul 18 '06 #10

Ron Natalie wrote:
Memset is a lousy way of initializing pods. It will work for
ints, but if mystruct had pointers or reals in it, there's no
guarantee that writing zero bytes all over it is the same as
assigning zeros to it.
That may be true theoretically but in practice I have never seen any
such implementation. Not that I've seen them all, but I've seen a few.
So for most that is a minor concern. More importantly though memset
doesn't work with non-pods and pods have a tendency to turn into
non-pods. That way you protect yourself against two cases: first, if
you ever add a copy op or virtual you don't have to go around switching
to this syntax; and second, if you ever decide a member needs a
different initial value than 0 you can build a default constructor and
not have to go around changing all your memsets. Finally, using the
construction syntax allows the compiler to do something else if it is
appropriate; you could end up with faster code and at worse no worse.

So, there are a few reasons not to use memset 0 but the theoretical
possibility of 0 not being 0 is not really a convincing one for most
people.

Jul 18 '06 #11
Victor Bazarov posted:

>myclass() {
static mystruct init; // this is default initialized

The storage is actually _zero_-initialised, and no other initialisation
is performed (remember, C++ is stupidly inconsistent when it comes to
PODs?)

I think (and sincerely hope) that you're mistaken.

The following code should set the array of pointers to their null value,
and the array of doubles to their zero value (... shouldn't it?):

int main()
{
double static array1[8];

void static *array2[8];
}
This syntax shown above should be directly equivalent to the following (...
shoudn't it?):
double static array1[8] = {};

void static *array2[8] = {};
--

Frederick Gotham
Jul 18 '06 #12
Frederick Gotham wrote:
Victor Bazarov posted:

>>myclass() {
static mystruct init; // this is default initialized

The storage is actually _zero_-initialised, and no other
initialisation is performed (remember, C++ is stupidly inconsistent
when it comes to PODs?)


I think (and sincerely hope) that you're mistaken.

The following code should set the array of pointers to their null
value, and the array of doubles to their zero value (... shouldn't
it?):

int main()
{
double static array1[8];

void static *array2[8];
}
This syntax shown above should be directly equivalent to the
following (... shoudn't it?):
double static array1[8] = {};

void static *array2[8] = {};
Yes, I've stated it incorrectly. Every static object is zero-initialised
(for pointers it means making them null, and for doubles making them 0.0)
at the start of the program (8.5/6).

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Jul 18 '06 #13
Victor Bazarov wrote:
>Unfortunately, one of the stupidest inconsistancies in C++ is
that default initialization does not always occur for PODs.

I find this hypocritical, Ron. You're enjoying the speed of your C++
programs thanks to omitting the initialisations for PODs, and then keep
bitching about them. Of course, I can be wrong about the enjoyment
part...
Nope, I've never bought that arugment. If unitialized data was
such a gosh-darn important speed feature, then some extra language
feature should be put in to support it. The big complaint was
that the speed would be degraded if you took unadulterated C
code and tried to cram that through a C++ compiler. I can tell
you as someone who moved about 800,000 lines of C code to C++
that is a entirely spurious argument.

I am however suffering from bugs where pods don't get initialized.
I'll take slightly slower over unpredictable and malfunctioning
everyday.
Please don't confuse things here. Zero-initialisation of the storage
of static objects has nothing to do with "default initialisation".
It
is not done because you didn't ask ("default").
Yes, but it because the defacto default initialization if other
initialization (static or dynamic) doesn follow along due to
explicit initializers.
>
...otherwise known as "value-initialisation"...
Don't get me started on freaking value-initialization. This idiotic
contraption was established to put bandaids on the "we don't always
initialize pods" concept.

C++ goes to great lengths to invent paradigms to describe that broken
C initialization rules coupled with the extensions for real
initialization (dynamic and consturctors and the like) that
C++ adds. It would have been so much easier to just initialize
everything and put warts on the syntax for the few times you don't
want initialization to take place.
Jul 18 '06 #14
seema wrote:
No their is no way i can declare a constructor in the mystruct because


Please don't top-post. Your reply belongs following or interspersed
with properly trimmed quotes. See the newsgroup FAQ:
<http://www.parashift.com/c++-faq-lite/how-to-post.html#faq-5.4>


Brian
Jul 18 '06 #15

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

Similar topics

3
by: sathyashrayan | last post by:
The standard confirms that the following initialization of a struct struct node { --- --- } struct node var = {NULL};
10
by: emma middlebrook | last post by:
Hi I discovered that if you declare a structure (and not 'new()' it) you can then separately initialize its members and the compiler counts those separate statements as a full initialization....
3
by: Karl M | last post by:
Hi everyone, I just notice some strange behaviors on the MS C++ compiler regarding struct default constructor, see the example bellow: struct MyStruct { int a; }; class MyClass { public:
4
by: hobbes992 | last post by:
Howdy folks, I've been working on a c project, compiling using gcc, and I've reached a problem. The assignment requires creation of a two-level directory file system. No files have to be added or...
6
by: arnuld | last post by:
this one was much easier and works fine. as usual, i put code here for any further comments/views/advice: --------- PROGRAMME ------------ /* Stroustrup: 5.9 exercise 7 STATEMENTS: Define a...
18
by: Ehud Shapira | last post by:
Is it possible to have a declaration of a struct pointer initialized to an unnamed struct? (I'm only concerned with static/global variables, if it matters.) I'm trying to do something like: ...
6
by: Daniel Rudy | last post by:
Hello Group. Please consider the following code: /* this table is used in the wipedevice routine */ static const struct wipe_t { uchar wte; /* wipe table entry */ } wipetable = {...
2
by: dj3vande | last post by:
Is this code, as the complete contents of a translation unit, valid C90 that initializes the struct foo to contain copies of the values passed to bar()? -------- struct foo { int i; void *v;...
10
by: Juha Nieminen | last post by:
I suppose you can never know C++ fully. I would have never guessed this actually compiles and works: struct Point { int x, y; }; struct Line { Point endpoint; int weight; };
5
by: ssylee | last post by:
I'm not sure if I can initialize members of a struct the lazy way. For example, let's say I have a struct defined as below: typedef struct _ABC { BOOL A; BOOL B; BOOL C; } ABC;
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...

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.