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


ADVERTISEMENT

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 :: Display Numbers That Are Passed As Literal ASCII Characters To LCD

Mar 20, 2014

What shall I learn in order to send values from 0.00 to 5.00? I'm working with they Hitachi 16x2 LCD display.I've been sending/displaying literal values on it all day.

Code:

SendCharater(unsigned char val)

where the variable val corresponds to the LCD character table.I can also send Hello World to the display, like so:

Code:

void putsXLCD(unsigned char *buffer){
while(*buffer) // Write data to LCD up to null
{
while( BusyXLCD() ); // Wait while LCD is busy
SendCharacter(*buffer); // Write character to LCD
buffer++; // Increment buffer
}
return;
}

I could type in putsXLCD("5.00") in order to display it on the LCD, but how do I implement this automatically for values, e.g. 0.00 to 5.00?It appears I can only pass literal values through the function SendCharacter, meaning that in order to display "0" I have to pass the value 0x30 (the hex value of "0" on the LCD Table).

My current thought process:Much like passing "Hello World" in the function putsXLCD(), I need to assign a pointer that points at each value in the "array" that I need to send. E.g., I need to send 3.24, so I need to point to "3", fetch the corresponding hex value in the LCD table, in this case 0x34, and the pass this 0x34 into the SendCharacter function, and so on. So, if this is the case, how can I fetch the corresponding hex value?

View 7 Replies View Related

C++ :: Unsigned Char To String And Being Passed Into Function

Mar 24, 2015

I have the following code, but it crashes on the "data = " line...

Code:
void Test(string& data) {
unsigned char* msg = (unsigned char*)malloc(MAX_LENGTH));
...
data = string(reinterpret_cast<const char*>(msg), MAX_LENGTH);
}

I know I could just return string, but what is wrong with this code that is making it crash?

View 6 Replies View Related

C++ :: Object That Is Passed To Function Is Changed Although No Pointer Is Passed

Mar 22, 2013

I am posting this simplified piece of code that is a bit confusing for me. There are two functions that I call. One shows the expected results but the result of the other one rather puzzles me.

//#define defineVecTyp Vec3f
#define defineVecTyp float
template <typename vecTyp>
vecTyp buildLaplacianPyramid(cv::Mat inputmat) {
vecTyp lapPyr;

[Code].....

Calling the function sum1 does not change the values stored in the variables val1 and val2. The output of the program is as follows:

val1= 1 ## val2= 10 // before the call of function sum1
val1= 1 ## val2= 10 // after the call of function sum1
sumOfVals= 22

This is quite obvious and as expected and I just pasted this piece of code as an example for better clarification.

However, if I call the function buildLaplacianPyramid and apply a function for Gaussian Blurring, this also effects the cv::Mat passed to the function. The line imshow("M1, after buildLaplacianPyramid",M1); therefore shows an image that is blurred. Since I am not passing a pointer to the cv::Mat I do not understand why this should be happening. I was assuming that there would be a copy of the cv::Mat M1 to be used within the function. Therefore I was expecting the cv::Mat M1 to retain its original value. I was expecting that all changes applied to cv::Mat inputmat within the function would not have any influence on the cv::Mat M1. Just like in my other example with the sum.

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

C :: Global Variable - Only Printf Works

Apr 20, 2013

Okay so I am programming an 8051 variant to interact with an SD card. In a separate initialization routine in SD_CARD.c I pull out the vital information of the card into global variables. I then call Menu() which is in another source file but includes a header file with all of the variables declared as extern. Now here is the weird, part this is from my Menu.c

printf("%u" , VOLUME_1_SECTOR);
if(VOLUME_1_SECTOR==16384)
printf("Correct");
else
printf("Incorrect");

Now the output of the first printf is 16384 but the conditional evaluates to false. If I put this code in SD_CARD.c (Where VOLUME_1_SECTOR is defined) the conditional evaluates to true. I am confused why the printf works correctly in Menu.c but not the conditional.

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++ :: 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

Visual C++ :: Local Variable Be Passed As Parameter Into A New Thread?

Apr 1, 2013

Can local variable be passed as the parameter for a new created thread procedure? Here is the example code:

Code:
void CDLG::some_function()
{
CString strFileName="abc.doc";
//local variable, can it be valid for being passed into the following new thread???
//Can strFileName still be accessed from within the stack of thread procedure?
::AfxBeginThread(ProcessContentThread,(LPVOID)&strFileName);
}

[Code]...

There is another method using variable on the heap,

Code:

void CDLG::some_function()
{
CString strFileName="abc.doc";
CString* pstrFN=new CString(strFileName);
::AfxBeginThread(ProcessContentThread,(LPVOID)pstrFN);
}

[Code]...

I test these code, both methods work as expected, but I doubt whether the first method is a good way. OR if only the second method is the correct way to pass a parameter to a thread.

View 12 Replies View Related

Visual C++ :: How To Directly Pass Wstring (literal) To Function

Feb 5, 2013

I am wondering if I have the following parameter to pass in to a function

Code : void Load(std::wstring filename);

This statement is wrong.

Code : Load("DataMesh.x");

I don't want to pre-declare a variable. How do I directly pass a wstring (literal) to this function.

View 2 Replies View Related

C :: How Getline Function Works

May 15, 2013

How the getline function works.

Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {

[Code] ......

getline(&inputstr, 128, NULL); getline gets a line in a data file.

I assume that inputstr[128] is the name of the file? why is the number of the array in the getline function....

View 7 Replies View Related

C# :: Get The Actual String Passed By Reference?

Apr 8, 2015

I have a list of Strings that are passed to a method consecutively by reference from a class. I want to get the string value passed to the method at a point in time. The reason is to perform an if statement.

//this is the class that holds that holds the constants.
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace xxx.Functional.xyz.Login {
public class Constants {
public static String Username = "paul";
public static String Code = "4";

[code].....

View 2 Replies View Related

C :: Array Sorting Program That Works With Recursive Function

Mar 10, 2013

i want to write an array sorting program that works with recursive function.but i can not do it.

my algorithm

Recursive
find the min value
find the min value and save it
find the min value and save it and remove it from loop
put the rest in loop again
find the min value again
..
...

i didnt write the function because i dont know how will it work

Code:

#include<stdio.h>
#include<stdlib.h>
#define s 5
void main() {
int a[s]={25,3,2,4,1},c[s]; // c[s] for new sorting
int i,ek,j; //ek = min

[Code]....

View 7 Replies View Related

C++ :: Creating Stand Alone Function That Works With Member Functions?

Nov 1, 2014

I was able to get this program running. Now I working on taking one of my member functions and turning it into a standalone function. I choose the create_board() function. Yet, if I declare it in my header file or my main.cpp it cant access any info from the original member functions?

main.cpp
#include "ticTacToe.h"
#include <iostream>
#include <limits>

[Code]....

View 2 Replies View Related

C++ :: Function Passed By Pointers Or Reference?

Sep 28, 2014

I am going to read some codes about image processing and I need to understand functions like this one below?

BOOL Trans_Geo_Affine(CImage *pImgSrc, CImage *pImgDst, BOOL bMatrix,
BOOL bHvInversed, double fScale_xx, double fFlex_xy, double fSkew_yx,
double fRotate_yy, double fTx, double fTy, int nInterpolation, BOOL bResize, BYTE cFill)

[URL]

two parameters, CImage *pImgSrc and CImage *pImgDst. I think they are class pointers and the function is passed by reference. What should I learn to understand this function and its parameters? How should I use this function? how to use the function with two parameters CImage *pImgSrc and CImage *pImgDst.

View 11 Replies View Related

C/C++ :: Values Passed To Put Function But Not Having Any Effect

Feb 9, 2015

I have this code:

tgaManager.fileWriter.put((unsigned char)min(blue*255.0f,255.0f)).put((unsigned char)min(green*255.0f, 255.0f)).put((unsigned char)min(red*255.0f, 255.0f));

that should pass the value decided by the min function to an ofstream object, filewriter, that call the put method to print chars in a tga image file. When I open the file, all I see it is a huge black screen. You may be thinking that the values of blue,green and red are all zero but it is not the case.

With this code:

if (x==50 && y==50) {
cout << "Min BGR: " << endl;
cout << min (blue*255.0f,255.0f) << ' ' << min (green*255.0f,255.0f) << ' ' << min (red*255.0f,255.0f) << ' ' << x << ' ' << y << endl;

I get: Min BGR: 9.54167 29.9188 47.8701 50 50

View 3 Replies View Related

C++ :: Cloning Object Passed By Function?

May 21, 2014

Is it correct for me to make a clone of testobj in function AddTest below, before i add it to my map? What i want is an user pass testobj to me though AddTest, and after i add it into my map, i do not want to have anything to do with the original testobj anymore. I.e, they are two copies, one belong to Device, one belong to the caller, both has no link to each other.

Also regarding the GetTest method, i prefer to return a raw pointer, as i do not want to force the caller to use smart pointer. And i also do not want the caller to be able to do anything that may change testobj in the map. So i am not sure to return as const reference or make a clone of testobj on the map and return it to the user (but caller need to delete the testobj when it is not used).

Code:

class Device {
public:
void AddTest(const Test* const testobj) {
_pTest.insert("ss", QSharedPointer<Test>(test->clone()));
} const Test* const GetTest(QString str) {
return _pTest[str].data();

[code].....

View 6 Replies View Related

C++ :: Convert Passed String Into Proper Alpha Case And Sort Array Of Names

Apr 25, 2013

I want to create 2 functions to (1) convert a passed string into proper case (capitalize the first alpha character of a string and every alpha character that follows a non-alpha character); (2) sort the array of names (after it has been converted to proper case).

I tried these two:

console.writeline (lower.toUpper());
void bubblesort (string array[],int length);

but I don't know if they are good.

View 2 Replies View Related

C++ :: Variadic Function - Parameters Get Passed In Reverse

Nov 17, 2014

I noticed that when using variadic functions, if I pass the va_arg() as parameter to a function, the parameters get passed in reverse. Is that expected?

For example, the following code outputs
Code:
1 2
2 1

Code:
#include <iostream>
#include <stdarg.h>

void foo_func(int v1, int v2)
{
std::cout << v1 << " " << v2 << std::endl;

[Code] .....

View 3 Replies View Related

C++ :: Function To Find Out How Many Days Have Passed Since Last Birthday

Feb 20, 2013

I have to write a c++ program with my own function which consists of two parameters (day, month). Function have to return number of days since the begining of this year. Using this function i have to find out how many days are left till birthday (or how many days have passed since last birthday)

This is how far i am:

Code:

#include <iostream>
using namespace std;
int cikDienu(int diena, int menesis);
int main()

[Code] ....

View 9 Replies View Related

C++ :: Pointer Passed To Function Value Doesn't Change

Dec 24, 2014

when i pass a string pointer to a function such as string *str = new string(""); and pass that string to a handleElement() function e.g. handleElement(str), and i change the value in the function it simply doesn't change when the function exits as though it's passing it by value or something, even though it gives the pointer address.. I've now changed the code to use double pointers and pass the reference of the str pointer and it works but it seems ugly to use double pointers for this.

//handles when a new element is encountered when parsing and adds it to the parse tree
bool ParseBlock::handleElement(char cur, string *curString, int count, bool isOperator) {
countNode = new ParseNode(count);
//keep track of numbers and strings if they exist and insert them
if(!curString->empty()){
if(isNumber(*curString)

[code].....

View 2 Replies View Related







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