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


ADVERTISEMENT

C++ :: Initializing Const Data Member

Apr 11, 2014

What I need to know is how I can pass an argument to the Book constructor so I can change the const data member Category (with cascading capacity if possible. I also posted some of my set functions for further comprehension.

class Book
{
friend void CompPrice(Book &,Book&); //friend function that has access to the member functions of this class
//The arguments sent to it are by address, and of type the class Book, so that it can have access to its member functions
private: //private data members

[Code].....

View 2 Replies View Related

C++ ::  Initializing Const Char Member Variable In Constructor?

Jan 23, 2015

I have a class that defines a window (a popup dialog of sorts), and I want the name of that window to be constant. The only problem is that the name of the popup needs to match the title of the parent window, and I get the name of the parent in the constructor. So how do I go about defining this member variable to be constant and initializing it with a value in the constructor?

I want to do something like this, but I know this isn't allowed:

/* class.h */
class foo {
public:
foo(*parentWindowPtr);

[Code] .....

I should mention that yes the name of the parent window is const char *, and I would like to keep it this way.

View 4 Replies View Related

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 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 View Related

C/C++ :: Taking String As Input And Making It As Whole Array (string Literal)

Oct 19, 2014

Very new to programming, and I know that there must be another way on inputting a string into each array cells not by just inputting it one by one, but as a whole. My code at the meantime is: [URL]

View 1 Replies View Related

Visual C++ :: Operator Overload Not Defined Error When Type Accessed Through Const Struct

Oct 17, 2012

I have a basic vector/point class where I've overloaded a bunch of arithmetical operators:

Code:
#pragma once
class point {
public:
point() {
}
point(float p_x, float p_y, float p_z) : x(p_x), y(p_y), z(p_z)

[Code] ...

I can use it fine like

Code:
point p(50,50,50);
point q(50,50,50);
point t = p * q + q;

However when I put this point type into a struct and try to access the members after passing it through by const reference:

Code:
struct sextic {
point a,b,c,d,e,f,g;
};
inline static sextic sexticDifference(const sextic &p_sextic1, c

[Code] ....

This gives me an "operator not defined" error for compilation.

View 2 Replies View Related

C++ :: String Literal With Constexpr

May 28, 2013

I have a binary identifier which I tried to make a constexpr since all of its calculations would never occur during runtime (this is true for literal identifiers, right?). Since constant expressions can only have one instruction, I tried to cheat a little and returned an immediate call to a lambda function. This failed miserably however. I tried making a constexpr function pointer and called that from _binary down below, but the compiler still felt that it wasn't a constexpr. Why is this? And is there a way to make a function like _b below constexpr?

#include <iostream>
#include <cstddef>
using std::cout;
using std::endl;
long unsigned //Original
operator"" _b(const char* const literal, size_t lsize){

[Code] .....

View 4 Replies View Related

C :: Assigning A Pointer To A String Literal

Sep 13, 2013

In another forum, this example code fragment was stated as being an example of undefined behavior. My understanding is that a literal string exists from program start to program termination, so I don't see the issue, even though the literal string is probably in a different part of memory.

Code: /* ... */
const char *pstr = "example";
/* or even */
char *pstr = "example";
/* as long as no attempt is made to modify the data pointed to by pstr, */
/* unless pstr is later changed to point to a stack or heap based string */

View 11 Replies View Related

C :: Free A String Literal From Memory?

Jan 8, 2014

This compiles o.k.:

Code:

int main(void){
char *a;
a = (char*) malloc (100*sizeof(char));

[Code]....

I get an error saying "pointer being freed was not allocated". This happens for free(a), free(*a), free(&a), free(&*a).

So if I no longer need "1234567"... how do I get rid of this memory element?

View 7 Replies View Related

C++ :: Use Of A Backspace Character In A String Literal

Apr 19, 2014

In the following char array, notice the use of a backspace character in a string literal: ''.

char text1[50] = "aHello,
World! Mistakee was "Extra 'e'"!
";

What exactly does a backspace character do here? When the compiler evaluates this line, does it actually delete the previous character, like when you press the backspace button on the keyboard?

View 1 Replies View Related

C/C++ :: Pointer-to-char To String Literal?

Oct 6, 2014

how string literal that works with the cin object?

char * str = "This is a string constant";

Is the str stored the address of the first character of the string literal?

But some books just state that the pointer-to-char (char pointer) stores the address of the string literal". So just wonder how it is.

When it is used with cout, cout just treats it like a string and instead of printing the address, it just prints out all characters one by one until it reaches the terminated null character.

If this is the case, then I am just wondering how cin works with it? with a statement like this cin >> str; ?

Does the computer allocate enough memory for it? and then cin stores the first character into the first address and then advances to the next address and stores the next character?

View 1 Replies View Related

C++ :: Function Works When Passed String Literal But Not A Variable

Jul 10, 2014

I'm making a .json loader for a project that I'm working on, and to simplify things, I decided to make all the root attributes named in a separate file. Here's my problem: my loading function, Add(const char* id), works just fine when I pass it a string literal.

However, when I use a function that iterates through a vector list, even with the exact same definitions as the literal, it returns the error: std::out_of_range at memory location 0x0026fb30

I've stepped through it with the VS2010 debugger about a hundred times, checked against memory locations, and just have done everything I can think of, all to no avail..

The code, with data-checking omitted:

The std::map I'm adding to:

static std::map<const char*, Item*> *s_mItems;
Initialized as std::map<const char*, Item*> *Item::s_mItems;

Add() Function (Works by itself with a literal):

static bool Add(const char* id) {
...
std::string name = node.Get("name").ToString();
std::string desc = node.Get("description").ToString();
int rarity = StrToRarity(node.Get("rarity").ToString());

[Code] ....

AddList() function, where the program always breaks:

static void AddList(std::vector<std::string> list) {
for(std::vector<std::string>::iterator it = list.begin(); it != list.end(); it++) {
Add(it->c_str());
}
}

View 3 Replies View Related

C/C++ :: SDL LoadBMP Fails To Load A Passed String Literal

Jan 24, 2014

Background: I'm using SDL and CodeBlocks and trying to make a Graphics class that would simplify some SDL operations such as drawing and loading images.

Issue: The loadImage function in the graphics class fails to load the image correctly and so the program prints out a blank window during run-time. I've tried multiple ways of passing a string literal into the function the surface temp fails to load and so background in Game fails to load. After testing it several times, I'm pretty sure that the issue lies with SDL_LoadBMP not registering the passed variable for whatever reason. I know the image is in the right place as writing SDL_LoadBMP("./Graphics/image.bmp"); brings it up just fine.

Current Code:

Main simply creates a Game object and execute(), so I didn't feel the need to put it on here.

Game.h
#ifndef GAME_H
#define GAME_H
#include "SDL/SDL.h"
#include "SDL/SDL_ttf.h"
#include "Graphics.h"
#include <string>
#include <cstring>
using namespace std;

//GLOBAL CONSTANTS
//game window settings

[Code] ....

Output: A blank window. (It should show the background image but doesn't.)

Note: I originally wrote it as gfx.loadImage(background, "./Graphics/image.bmp") but that gives me a conversion warning and still fails to show the image when the program runs. I've tried looking up examples similar to what I was doing but no one else seems to have this problem.

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++ :: String To Const Char Error

Jan 15, 2013

I'm currently finishing up an assignment that was half written by my professor. Below in the testGrades section of code there are two errors both are the same message.

Error: no matching function for call to Grades:: Grades(const char [15])

Test Grades

//Purpose: Test program for the class Grades
// Create stu1 Grades object
// Add 5 grades to stu1 - only 3 can be stored in stu1 - other 2 discarded
// Create stu2 Grades object
// Add only 2 grades

#include <iostream>
#include <string>
#include <iomanip>
#include "Grades.h"

using namespace std;

[Code] .....

View 5 Replies View Related

C++ :: Class Constructor With String Const Pointer As Parameter

Feb 19, 2013

I know my product.cpp constructor is wrong but how can I set my private variables.

//PRODUCT.h
#ifndef PROJECT1_PRODUCT_H
#define PROJECT1_PRODUCT_H

[Code].....

View 2 Replies View Related

C++ :: Const Method Accessing Private Data Member Giving Access Violations

Oct 17, 2014

My code is here [URL]

void Player::Display() const
{
cout << "
Player Name: " << GetName() <<
"
Grade: " << GetGrade() << "
G.P.A. " << GetGPA() << endl;
}

The problem occurs in here, I get access violations, is there a way to this while keeping Display const or is this code valid and my problem is somewhere else and not being caught in the debugger? I tried to make the return types const - but that didn't work .....

//Getters need const twice for this to work?
const char* Player::GetName() const {return m_name;}
const int Player::GetGrade() const {return m_grade;}
const double Player::GetGPA() const {return m_gpa;}

[Code].....

View 2 Replies View Related

C++ :: Initializing Multidimensional String Array?

Nov 15, 2014

In one of my programs I have a 3x3 array of string that I use to display the outcome to rock, paper, scissors, and another 1x3 used for a number guessing game. I have the arrays declared in the header file as follows:

//Games.h
std::string rpsOutcome[3][3];
std::string hiLoOutcome[3];

and then initialized them in the cpp file:

//Games.cpp
string rpsOutcome[3][3] {
//row 1
{ "Both of you picked rock, you tied. Try again",
"You picked rock, the computer picked paper, you lose",

[code]....

From what I've read, Im pretty sure thats how your supposed to initialize multidimensional arrays (using the nested braces), but when I build the project, I get the following error:

123456789101112
1
1> RockPaperScissors.cpp
1> Games.cpp
1>c:userswuubbgoogle drivevisual studio projectsgamesgamesgames.cpp(75): error C2374: 'games::rpsOutcome' : redefinition; multiple initialization

[Code] .....

View 4 Replies View Related

C++ :: Initializing Array Of String Type In A Class

Apr 28, 2013

I want to use this array as part of my class. I have tried several different angles trying to get it to work but with out success. I have been checking to see if it works by simply using "cout << dayName[3];" It is printing nothing at all. What is the proper way to initialize this array of strings?

First I tried this:
const string dayName[] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};

then I tried this:
const string dayName[7];
dayName[0] = "Sunday";
dayName[1] = "Monday";
dayName[2] ="Tuesday";
dayName[3] ="Wednesday";
dayName[4] ="Thursday";
dayName[5] ="Friday";
dayName[6] ="Saturday";

My implemetation file code and my header file code is here (header first):

//dayType.h, the specification file for the class dayType
#include <iostream>
#include <string>
using namespace std;
class dayType{

[Code] .....

View 4 Replies View Related

C++ :: Calling Const / Non-const Overrides

Oct 5, 2013

Are there other ways of calling a const/non-const override? I want to defined some functions in terms of others, particularly accessors which might or might not require constness- in order to not copy & paste code. This is my current solution:

struct dumbArray {
dumbArray(unsigned int size):
m_array(new int[size]){
}
~dumbArray(){
delete m_array;

[Code] .....

View 10 Replies View Related

C++ :: Difference Between Const And Static Const

Dec 7, 2013

difference between const and static const, more effectively. I know the basic concept of const and static but I need clear explanation of declaring "const" and "static const"

Ex:

const int a;
static const int a;

View 5 Replies View Related

C++ :: Casting Non-const Variable To Const

Jun 19, 2013

Is there any way to cast a non-const variable to const one?

I want to read variable n from file and then use it to declare array "int arr[n]", but because n is non-const, the compiler doesn't allow me to do that.

View 6 Replies View Related

C++ :: The Difference Between Const And Non Const Key

Jul 13, 2013

So I start thinking about what's the difference between this 2 code

map<const int, float> map_data;

map<int, float> map_data;

But it seems I can't find the difference, is there any difference between this 2 code ?

View 1 Replies View Related

C++ :: Outputting Associated Data In Struct

May 2, 2013

So this is the last part of a program I've been working on for four weeks now. This question may be a tough one considering the amount of files included in the program.

The program is to read in a file of requests between two cities, read in a file of flights and cities that occur between the cities. It then checks to see if there is a path between the flights and output an itinerary. I have the correct itinerary outputting, but when attempting to output the associated flight number and price according to the city, I am getting odd data. How can I output the correct flight number and price associated with each flight on the itinerary.

I'll post out the output I am currently getting and the section where I am outputting the data. I'm sure I'll need to post more files so the program can be understood.

Don't want the code done for me, just a point in the right direction! I don't want to let this program defeat me!

Output: Code: Request is to fly from Atlanta to San-Diego.The flight itinerary is:
Flight # From To Cost
10 Atlanta Chicago $134529069
10 Chicago Miami $134529069
10 Miami Dallas $134529069
10 Dallas San-Francisco $134529069
10 San-Francisco San-Diego $134529069
This function finds a path between cities. Code: bool flightMap::IsPath(string originCity, string destinationCity){
StackClass aStack, bStack;
flightStruct flightRec;
string topCity, nextCity;
bool success;
int index = 0;

[Code].....

View 1 Replies View Related

C :: Initialize Data Member In Struct

Mar 28, 2013

I was looking at some linked list material and was wondering something. Can you initialize a data member inside a struct like in C++? i.e.

Code:
typedef struct node
{
int data;
struct node * next = NULL; // this is the line in question
} LLnode;

View 3 Replies View Related







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