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


ADVERTISEMENT

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/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++ :: 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 :: 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++ :: 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++ :: 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 :: Assigning Value To Char Pointer

Feb 3, 2013

I thought we needed to allocate memory before assigning a value to a char* and also that we needed to use functions like strcpy() to copy something into it. Then how come this works and does not crash?

Code:
#include <iostream>
using namespace std;
int main()
{
char * buf;
buf = "Hello";
cout << buf << endl;
buf = "World!!!!!!!!";
cout << buf << endl;
return 0;
}

View 3 Replies View Related

C :: Assigning Value During Pointer Declaration

Aug 31, 2013

I am trying to understand the behavior of following code. Basically how does printf() prints the value rather than address.

Does initializing value to a pointer during declaration makes a difference when assigned from a variable?

Code:

1 #include <stdio.h>
2
3 int main() {
4 const char *var1 = 'A';
5 int *vint = 10;

[Code] ....

View 8 Replies View Related

C++ :: Using Pointer In Union And Assigning Value

Jul 2, 2013

In the current code,We are using pointer of union and assigning value.

class sample {
union {
short *two_int;
int *four_int;
double *eight_real;
char *one_ascii;
// void *v;
}; }

Than we assign value in following way.

sample.four_int[0] = (x + xoff); ( x and xoff and y and yoff all are integer)
sample.four_int[1] = (y + yoff);

Than we write data into file. it was working fine into 32 bit machine but it is not working 64bit machine. When I compare data and found that data is divided by 4. For Ex The File generating from 32 bit machine contain 80 than 64 bit . File contain 20.

View 7 Replies View Related

C++ :: Assigning Address To Object Pointer

Aug 16, 2013

I have the following code.

StackElement *StackElementArray;
StackElementArray = new StackElement[iMaximumDepth];

I want to assign one element of this array StackElementArray the address of another object. For example,

voidStackMem::push(StackElement &iStackElement) {
CurrentDepth++;
StackElementArray[0] = iStackElement;
}

The StackElement class contains pointers to some dynamic arrays. When I use the assignment, StackElementArray[0] = iStackElement;, it doesn't copy the complete contents and I have to define an 'assignment operator' function to copy all the contents. I am wondering if there is a way I can assign StackElementArray[0] the pointer to the StackElement object. In that case, I will not need to copy the contents of iStackElement into StackElementArray[0] and will just copy the address.

View 3 Replies View Related

C++ :: Assigning Pointer In Node To Point To New Vector

May 9, 2013

I've got a struct called Node that contains, among other things, a pointer to a vector of pgm objects. (pgm is a class i've created)

struct Node {
int label;
vector <pgm> *ptr;
Node* lessNode;
Node* moreNode;
};

in another class, i create a vector and a Node and am having trouble assigning the pointer in the Node to point to my new vector.

vector <pgm> lessData;
Node* left;
left->ptr=&lessData;

This all compiles ok, but the last line in the code above causes a segmentation fault. I should mention Node is declared on its own in Node.h and what pgm is. including pgm.h in node.

View 2 Replies View Related

C/C++ :: Assigning Pointer (int) Located In Main With Another Function

Aug 2, 2014

I have the following:

int Allocate(int, int *);
main() {
int *Pointer;
int Elements = 25;
// this works just fine - as expected.
Pointer = (int *) malloc(Elements, sizeof(int));
// This DOES NOT - The value of Pointer never changes.....

[code]....

View 2 Replies View Related

Visual C++ :: Error Assigning Pointer To Iterator

Nov 27, 2014

im trying to port a code from vc6 to vs2013 and im having this error

Code:

Error11error C2440: 'initializing' : cannot convert from 'char *' to 'std::_Vector_iterator<std::_Vector_val<std::_Simple_types<char>>>' on this line

Code:
vector<char>::iterator BufIt = (char*)lpBuffer;

what i do with this is to stack fragments of data of type char* coming from a socket in buffer to a vector that acts as buffer, I do this since I transfer big chunks of data and the data gets fragmented by the nature of the sockets, I stack the data once its complete I retrieve the final result from the vector.

this code worked flawlessly for long time but now Im trying to port and compiler throws this error, whats the new way to assign a char array pointer to a iterator so i can stack it in the vector.

View 5 Replies View Related

C++ :: Assigning String Tokens To Array?

Oct 20, 2014

I need to dynamically build a control file for a SQL loader but when tokenizing line values read from a file i am unable to work/assign the last value to a variable even though i can print the actual token value while in the loop.

Below is the code snippet i have and get:

Code:
//headElement declared as headElement[42]
//getCol function is used to decode column keys present in line being read
istringstream ss(line);

[Code] .....

I've attached a sample file as well.

View 1 Replies View Related

C :: Assigning String To Array And Compare It?

Mar 20, 2013

I have this code :

#include <errno.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>

[Code] ...

And this error occued with me I don't know why ???

myHeader.h:42:19: error: expected ")" before string constant

This code is compiled from file called myHeader.h ...

View 2 Replies View Related

C :: Assigning Line Of File To String

Mar 28, 2014

I'm making a game that requires the user to enter a correct username and password to play. I have a list of accepted ones saved in a txt file. How do i read each line of the file and check it with the one entered? I know how to use strcmp(string1, string2). I just need to know how to move from one line to the next. This is what I have for this part of the program so far. Also, I think im using the feof() wrong.

Code:
id = fopen("F://CS223/namepass.txt", "r");
score = fopen("F://CS223/scores.txt", "a");
srand(time(NULL));
if(id == NULL)
{
printf("ERROR");

[Code] .....

View 6 Replies View Related

C++ :: Assigning String Tokens To Array?

Oct 20, 2014

I need to dynamically build a control file for a SQL loader but when tokenizing line values read from a file i am unable to work/assign the last value to a variable even though i can print the actual token value while in the loop.

Below is the code:

//headElement declared as headElement[42]
//getCol function is used to decode column keys present in line being read
istringstream ss(line);
wfile << "LOAD DATA " << endl <<
"INFILE * " << endl <<

[code]....

View 5 Replies View Related

C++ :: How To Convert Void Pointer To Int / Double / String Pointer

Mar 7, 2013

I have a function:

const void insertStuff(const void *key, const int value){
// I want to convert the void pointer into one
// of three types of pointers(int, string, or double)
switch(value){
case 0:
int *intPtr = key;

[Code] .....

But this causes an error of: "crosses initialization of int*intPtr"

What's the correct way of implementing this?

View 1 Replies View Related

C++ :: Write A Loop Assigning Variable X To All Positions Of String Variable

Sep 8, 2013

I have to write a loop assigning a variable x to all positions of a string variable and I'm stuck. I don't have extensive experience with arrays and I'm also a bit confused about C-String. The problem is below.

"Given the following declaration and initialization of the string variable, write a loop to assign 'X' to all positions of this string variable, keeping the length the same.

char our_string[15] = "Hi there!";

(Please note this is a 'C-string', not C++ standard string.)"

View 5 Replies View Related

C/C++ :: Copying A String From A Pointer To New Pointer

Mar 4, 2015

I need to make a copy of a string that is defined by char *full and copy it into a different pointer defined by char *duplicate. I have written code to do this however it will not work and i cannot figure it out my code is as follows:

char *duplicate = (char *)malloc(strlen(full) + 1);
strcpy(duplicate, full); /*Make second version of full*/
char *Ptr = strtok(duplicate, " "); /*Split duplicate up*/

I have a full program written but i know this is where the problem is because i have used printf statements to see where the program fails. I get no errors and it compiles successfully but it hits this point of the program and it just stops and windows automatically shuts down the program.

char *full is pointing to:
"To be, or not to be? That is the question:
Whether 'tis nobler in the mind to suffer
The slings and arrows of outrageous fortune,
Or to take arms against a sea of troubles,"

I need to duplicate the string because i need to use strtok but i will need the original string later on so i need an unaltered version.

View 9 Replies View Related

C# :: Instantiation Of Literal Strings?

Apr 5, 2012

I have a huge xml file from which the key and value attributes are selected among other things.

Code:
foreach (
XmlNode node in
configProductCode.SelectNodes("/configuration/appSettings/add"))
{
ConfigProductCode cpc = new ConfigProductCode();

XmlAttribute keyAttr = node.Attributes["key"];
XmlAttribute valAttr = node.Attributes["value"];
// etc
}

How does C# handle the instantiation of literal strings? does it make a new object with allocating heap memory on every iteration or just once?

View 2 Replies View Related

C :: String Allocation To String Pointer

Feb 10, 2014

I am trying to read the string from user and the allocate it to the another string which is ptr string but not successful . Do I have to use any dynamic memory allocation here?

Code:
int main(){
char test[5];
char *strng, *base;
int i;
base=strng;
for(i=0; i<4; i++){

[Code]....

View 8 Replies View Related

C++ :: Create User Define Literal?

Jul 14, 2014

In C++ there are a number of primitives that are not defined in terms of other types. By this I'm thinking

int a = 1;
char b = 'M';
float c = 3.45f;
short d = 0xC3A3;

Is it possible to define your own literal? What I would like to do is have a hex literal for a data type where n = sizeof(data_type). If this type were a big integer, then I would want something like:

BigInt e = 0x13CA9B0C98D983E912DA0B0A9F87E0;

My goal is to assign a value from one contingous chunk of bytes and to not do it with a string.

View 1 Replies View Related







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