C++ :: Initializing A POD Bitfield Struct?

Apr 14, 2014

I'm wondering what is the "best" way to initialize a bitfield struct. I have this bitfield, defined as:

Code:
struct S
{
unsigned int a : 1;
unsigned int b : 1;
};

If I'm "using" the bitfield, I can initialize it easily when declaring it, as so:

Code:
int main()
{
S s = {0};
}

Now, the issue I'm facing is that I want to embed S inside another struct, which I'll name "outer". EG:

Code:
struct Outer
{
S s;
};

I'm wondering what the "best" way to have Outer initialize S is? I've seen a lot of people use the "union" approach:

Code:
struct Outer
{
Outer()
{
u.all = 0;
}
union
{
unsigned char all;
S s;
} u;
};

but:This adds an extra field depth (the union's u)Does bit hacking, in a way (is the bitfield as large as my field?) I'd have wanted to initialize the field in my constructor, as so:

Code:
Outer::Outer() : s({0})

However, this would appear to be a C++11 feature only.

I have, however, "observed" that by simply "empty constructing" s, eg:

Code:
Outer::Outer() : s(){} //Initialize s ?
vs
Outer::Outer(){}

Then my bitfield "appears" initialized.

View 5 Replies


ADVERTISEMENT

C++ :: Initializing Struct On Declaration

Dec 20, 2013

Code:

struct foo {
char label[64];
int state;
} bar[3] = { };

Will the above code ALWAYS initialize to 0 all objects:

bar[0].label
bar[0].state
bar[1].label
bar[1].state
bar[2].label
bar[2].state

Using gcc and g++, it does in my testing But was wondering if it can be unsafe under some circumstances.

I even tried without = { } and it is still initialized to 0 for all objects!

View 5 Replies View Related

C++ :: Initializing Const Struct When Data Is A String Literal

Feb 23, 2015

I have a struct like this:

Code:
struct String{
char* data;
std::size_t size;
};

I would like to be able to create const variables of this type for string literals.

Code:
const String message;

Is there an elegant way to create a const String like this when data is a string literal?

I tried this:

Code:
const char *string_data = "Hello";
size_t string_size = strlen(string_data) + 1;
const String string = {string_data, string_size};

The problem with that is that string.data isn't considered const during the initialization of the String struct so the compiler throws an error. It doesn't feel very elegant to do it like this either way.

Is there an elegant solution to this problem? I would like to avoid making a copy of the string literal.

View 7 Replies View Related

C++ :: Finding The Address Of A Bitfield

Aug 14, 2013

So I obviously can't take the address of a bitfield, but is there a way to get the address of the field holding the bitfield? What I'm trying to do is find the address of the parent field of a bitfield in a class. For example

Code:
class Foo
{
public:
int a;
int b : 4;
int c : 28;
[Code] ....

My goal is to get the offset address of the int storing c in class Foo. But offsetof uses the address of c, so I get a compile error since c is a bitfield. What I wanted as output from the above would be "4", since an int is 4 bytes (on my system). So the int holding both b & c starts 4 bytes from the start of the Foo class. Is there any way to do this in c/c++?

View 14 Replies View Related

C :: Bitfield Array - Using Standard Technique Of Creating A Structure Within Union

Mar 27, 2013

Any way that one could create a bitfield using the standard technique of creating a structure within a union, as follows:

Code:
typedef union {
struct {
unsigned b0 : 1;
unsigned b1 : 1;
:
:
unsigned b(n-1) : 1;
} bits;
unsigned int value;
}

BIT_FIELD_TYPE; Except, what I'd like to do is to replace all the single-bit elements in the bits structure with a single statement that creates an array of, say, 32 values. The clear advantage of this is that it could be traversed using an iterator, ...

Code:
main() {
BIT_FIELD_TYPE foo;
unsigned int i;
...
for (i = 0; i < n; i++) {
... (print out foo.bits.b[i]) ...
}

So far, I've not figured out a way to do it, either as an array, or using a pointer to iterate through the individual bits.

View 6 Replies View Related

C/C++ :: Sizeof (struct) Returns 6 More Bytes Than Actual Struct Size?

Sep 14, 2014

#include <stdio.h>
#define MAX_USERS 20
struct {
char ID[10];
char Name[40];
int Pos;

[Code] .....

I was attempting something weired with address to move data around when I discovered that the size of the array is not what I expected. I am passing this structure as &Users to a function that declares it as a void *, then I can deal with chunks of data (memmove) and not have to worry about index or things like that. However...sizeof is returning something I do not understand.

View 9 Replies View Related

C++ :: Creating A Struct Within Struct Node?

Feb 28, 2015

Im having trouble creating a struct within a struct node. the program suppose to hold students firstname, lastname, and gpa in a node therefore creating my linked list. Line 26 keeps saying that cannot convert parameter 2 from 'studentType to std::string

#include <iostream>
#include <string>
using namespace std;
struct studentType{
string firstname;
string lastname;
double gpa;

[code].....

View 2 Replies View Related

C++ :: Constructor Not Initializing Array?

Mar 6, 2015

I am making a tictactoe program that requires me to have a 3 by 3 two dimensional array of integers, in which the constructor should initialize the empty board to all zeroes. The program complies, but it keeps outputting garbage values and i'm not entirely sure why, My print function isn't complete yet, since I want to print out the array in a tic tac toe format, but i'm more concerned with why it's printing garbage values, here is my code:

Code:

// header file
#include <iostream>
#include <array>

[Code] ....

View 7 Replies View Related

C++ :: Initializing Variables In Each Class

Sep 26, 2014

I am working on a homework assignment and have most of the program working, but when I try to compile it keeps telling me to initialize the coin variables in each class. However, they are supposed to be added then removed so I don't want to set them back to zero.

Rewrite the Purse program given in Page 35 with functions to perform insert and remove operations. The function insert (int p, int n, int d, int q) will initialize pennies, nickels, dimes and quarters. The function dollars() will return the dollars. The function remove (int p, int n, int d, int q) will subtract pennies, nickels, dimes and quarters. The function display() returns a new String to print the content of the purse with remaining pennies, nickels, dimes and quarters.

Code:
usingnamespace std;
int insert_money (int *p, int *n, int *d, int *q);
int remove_money (int *p, int *n, int *d, int *q);
int dollars();
int main()

[Code] ....

View 2 Replies View Related

C :: Initializing Paging In Kernel

Oct 7, 2014

I am having issues with trying to implement JameM's kernel. I page fault attempting to assign the return value of place_ordered_array into the kheap.The malloc function should remain between 10000000-20000000 yet I exceed this. I have a hunch it's due that I am using grub2 (he uses legacy) and it loads modules at a higher address. I tested this by debugging at alloc and found that the function cannot handle above about 20000000. Am I on track to say I must attempt to move the module or code to prevent trampling or that I should switch to legacy.

View 1 Replies View Related

C++ :: Initializing Static Member Just Once Throughout

Jul 24, 2014

Here I'm trying to initialize PersonFactory::ethnicSurnames just once for the entire run of the program:

#include <iostream>
#include <string>
#include <vector>
#include <array>

enum Country {India, China, France, NumCountries}; // plus many other countries
struct School {}; struct Mall {}; struct HockeyArena {};

[Code] ....

Output:

PersonFactory::initializeEthnicNames() called
Carrying out the initialization...
PersonFactory::initializeEthnicNames() called
PersonFactory::initializeEthnicNames() called
PersonFactory::initializeEthnicNames() called
PersonFactory::initializeEthnicNames() called
numberOfTimesInitialized = 1

As you can see, even though five PersonFactory objects were constructed, the ethnicNames initialization only occurred once, as desired. However, there are some issues with my method. First of all, the use of the comma operator is ugly in my opinion. But fashion statements aside, PersonFactory::initializeEthnicNames() is still called multiple times, which is not good, even though it correctly avoids reinitializing ethnicNames after the first call. Also, I now forever get the annoying compiler warnings that the bool namesInitialized is never used, which is true, thus wasting a small bit of memory. And finally, I cannot declare ethnicNames const now, and it is supposed to be const. Any better way to accomplish what I'm trying to do?

By the way, the reason why I don't initialize ethnic names outside the class as is normally done for static data members (and that would indeed allow me to declare it const) is because it would get messed up if I later change the order of the elements in enum Country. Hence actual lines of initializations I think are needed. And I do want ethnicSurnames inside PersonFactory, because I feel it really does belong there. Also, PersonFactory is not to be Singleton, because it has data members that depend on some parameters in its constructor (e.g. geographic location).

View 5 Replies View Related

C++ ::  initializing Variables In Program

Oct 24, 2013

I want to know how to make variables during the program. for example in a program i want to have the player be able to create their own spells or add their own weapons to the game without having to edit the source code. i use sfml 2.0

View 4 Replies View Related

C++ :: Initializing A Class To A Pointer?

Feb 4, 2014

I came across a piece of c++ code that seems to be initializing a class object like this:

ImapMailbox *mailbox;

Now the class looks like this:

class ImapMailbox {
public:
ImapMailbox();
ImapMailbox (const QString& mailbox);
~ImapMailbox();
// Methods
void addMessage (ImapMessage *message);

[Code]...

And the constructor looks like this:

ImapMailbox::ImapMailbox()
: d(new ImapMailboxPrivate)
{
d->unseen = d->exists = d->recent = 0;
d->readWrite = false;
d->flags = 0;
}

But this does not seem to be an array like object. So what exactly could this be pointing to?

View 2 Replies View Related

C++ :: Initializing Object Through Constructor

Oct 15, 2013

sth is in my mind.

fast way of initializing an object through constructor is

Fred::Fred() : x_(whatever) { }

slow way
Fred::Fred() { x_ = whatever; }

ok. i accept it is faster but why?? what is the difference compiler does.

View 6 Replies View Related

C++ :: Variable Not Being Declared Before Initializing - But It Is?

Mar 31, 2014

I'm working on this program, and when i run it for 'p', 'P', or for a incorrect service code a error message pops up saying that "totalCost is being used without being initialized". I don't want to change it to switches, case, and breaks now because I've come too far to change it all. I have that variable right here just below.

#include <iomanip>
#include <iostream>
using namespace std;
int main() {
int acctCode;
double nightCost;
double totalCost;

[Code] ....

View 4 Replies View Related

C/C++ :: Initializing Pointer To NULL?

May 17, 2014

So I'm writing a small program for class, and for some reason I keep getting an error when trying to initialize head to NULL. Even threw in the namespace just to see, nothin'.

#ifndef NUMBERLIST_H
#define NUMBERLIST_H
using namespace std;

[Code].....

There's my header file. Not sure what I'm doing wrong with the constructor.

EDIT: Got it to work with nullptr, but still curious why that isn't working

View 2 Replies View Related

C/C++ :: Initializing Array Of Structures

Feb 25, 2014

How to initialize this array of structures in my code

struct CustomerAddress; {
string street;
string city;
string state;
int zip;

[Code] ....

I am going to be using a boolean variable to mark whether or not a specific field has had data entered into it. I figure the best way to do that is to initialize all the elements of the structures to 0. However, with strings and with the nested structure, I'm not sure how to do this.

View 6 Replies View Related

C/C++ :: Initializing Constructor In CPropertyPage?

Aug 21, 2013

Here is a declaration of property class
class CMyPropertyPage11 : public CPropertyPage

Here is the definition
CMyPropertyPage11::CMyPropertyPage11() : CPropertyPage(CMyPropertyPage11::IDD)

I really do not understand the role of the
CPropertyPage(CMyPropertyPage11::IDD)

But I need to derive CMyPropertyPage11 from another CPropertyPage, say CBasePropertyPage adn really need to know how to implement the CPropertyPage(CMyPropertyPage11::IDD) initialization again.

View 3 Replies View Related

C++ :: Accessing Inside Structure Via Struct Pointer To Struct Pointer

Jun 5, 2012

"
#include <stdio.h>
struct datastructure {
char character;
};
void function(struct datastructure** ptr);

[Code] ....

These codes give these errors:

error: request for member 'character' in '* ptr', which is of non-class type 'datastructure*'
error: request for member 'character' in '* ptr', which is of non-class type 'datastructure*'

These errors are related to
"
*ptr->character='a';
printf("Ptr: %c",*ptr->character);
"

I want to access "character" data inside the structure "trial" by a pointer to pointer "ptr" inside function "function",but I couldn't find a way to do this.

View 3 Replies View Related

C :: Segmentation Fault -> Main Not Initializing

Mar 14, 2013

This program is compiling just fine but is not running. Even, Main is not initializing, Here is my code

Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int pow2(int n) {
printf("POW2");
int pow = 1;

[Code] ....

View 2 Replies View Related

C++ :: Initializing Double Pointer Array?

Aug 1, 2013

How to initialize double pointer array..?

int (**aLines)[2];

View 3 Replies View Related

C++ :: Reading In And Initializing Data From File

Oct 30, 2014

Im familiar with fstream and know how to read in data, given that there is one type per line.

But I have a file that has multiple lines each containing a string (an address) and two double values (latitude and longitude).

Looking for support with the logic part of reading in data and initializing them to member variable.

View 1 Replies View Related

C++ :: Initializing 2D Dynamic Array With All Entries 0?

Dec 29, 2013

is it possible to create a dynamic array with all entries in it equal to 0?

int** adjMatrix;
adjMatrix= new int*[numOfVertices];
for(int i=0; i<numOfVertices; i++){
adjMatrix[i]=new int[numOfVertices];
}

View 1 Replies View Related

C++ :: Error Initializing Map - Ambiguous Operator

Feb 9, 2014

Okay so inside my ArcherArmor.cpp, I'm trying to figure out why the map initializer list isn't working, but for some reason I keep getting "Error C2593: 'operator =' is ambiguous". Here is my code:

I also have a class which ArcherArmor is derived from, that has a struct called `Armor`, which I left out for simplicity. The main problem is that error! The only thing I can think of is that im initializing the map wrong.

//ArcherArmor.h
#include <string>
#include <map>
class ArcherArmor {
private:
map <int, Armor> soldier_armor;
public:
void ArcherArmor_shop();

[Code] .....

View 7 Replies View Related

C++ :: Initializing Map - No Matching Constructor For Initialization

Nov 18, 2014

I am trying to create a `std::map` from `std:: string` to a pointer to member function type. I'm initializing the `map` with an initializer list (braced). When I compile, I get a message from the compiler: No matching constructor for initialization.

Example: [URL] .....

View 4 Replies View Related

C++ :: Initializing Local One Dimension Array?

Jul 31, 2013

Want to initialize a local one dimensional array. How can I do the same without a loop?

Found from some links that
int iArrayValue[25]={0};
will initialize all the elements to ZERO. Is it?
If yes then can we write below code to initialize the elements to a non-ZERO value?

int iArrayValue[25]={4};

Do we have some other way to initialize an array to a non-ZERO value? Memset can initialize the element to ZERO.

View 7 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved