const char* = new char[6]

S

S S

Hi Everyone

I have

const char *p = "Hello";

So, here memory is not allocated by C++ compiler for p and hence I
cannot access p[0] to modify the contents to "Kello"
p[0] = 'K'; // error at runtime

So I did

const char *p = new char[6];

But then how do I initialize it to "Hello"? My requirement is - I want
a const char* initialised and later want to modify the contents.

I know a way as written below

const char p[] = "hello";
const_cast<char&>(p[0]) = 'K'; //OK

But how to acheive this with pointers?

What I know is - C compiler allocates memory when I do
const char* = "hello";

But C++ compiler does not do that. Any help is welcome.

Thanks
SS
 
K

Kai-Uwe Bux

S said:
I have

const char *p = "Hello";

So, here memory is not allocated by C++ compiler for p and hence I
cannot access p[0] to modify the contents to "Kello"
p[0] = 'K'; // error at runtime

So I did

const char *p = new char[6];

But then how do I initialize it to "Hello"? My requirement is - I want
a const char* initialised and later want to modify the contents.

That will always be undefined behavior, regardless of what you try.
Modifying an object that was declared const is simply a no-no.

I know a way as written below

const char p[] = "hello";
const_cast<char&>(p[0]) = 'K'; //OK

Nope, not OK. It's undefined behavior. It may work on your platform -- for
now.

But how to acheive this with pointers?

What I know is - C compiler allocates memory when I do
const char* = "hello";

But C++ compiler does not do that. Any help is welcome.


Best

Kai-Uwe Bux
 
R

Rolf Magnus

S said:
Hi Everyone

I have

const char *p = "Hello";

So, here memory is not allocated by C++ compiler for p

p is only a pointer. The compiler does allocate storage for the pointer
itself.
and hence I cannot access p[0] to modify the contents to "Kello"
p[0] = 'K'; // error at runtime

The compiler allocates storage for the string literal, but as a constant. So
you can access it, but you're not allowed to write to it.
So I did

const char *p = new char[6];

But then how do I initialize it to "Hello"?

You can't directly initialize it. You can use strcpy to copy the literal
over to your array, like:

strcpy(p, "Hello");

However, that won't work without a cast unless you remove the 'const'.

Btw: Don't forget to delete your array as soon as you don't need it anymore.
My requirement is - I want a const char* initialised and later want to
modify the contents.

If you want to modify it, don't make it const.
I know a way as written below

const char p[] = "hello";
const_cast<char&>(p[0]) = 'K'; //OK

Why do you make the array const if you want to write to it? Just do:

char p[] = "hello";
p[0] = 'K';
But how to acheive this with pointers?

char p[] = "hello";
char* ptr = p;
ptr[0] = 'K';

But why do you actually want to have a pointer here?
What I know is - C compiler allocates memory when I do
const char* = "hello";

But C++ compiler does not do that.

There is no difference between the way C treats the above line of code and
the way C++ does.

Another question: Why do you use raw pointers to char instead of
std::string?
 
R

Ron Natalie

S said:
const char *p = "Hello";

So, here memory is not allocated by C++ compiler for p and hence I
cannot access p[0] to modify the contents to "Kello"
p[0] = 'K'; // error at runtime

No, that is not correct. First, you need to understand two things.
P is a pointer. It is a variable that holds the address of a char.
The memory for p itself is allocated in the context it was declared
(most likely local to a the function that contains it).

"Hello" in this context is allocated by the implementation at some
unspecified location as a array of (const) chars, this value is
converted to a pointer and stored in p.

First, your error should have happened NOT at runtime. The compiler
should reject at compile time the access violation of storing into
a const char.

Even if you were not to use const here:
char* p = "Hello";
p[0] = 'K';
is undefined behavior. The string literal memory is not allowed
to be changed (the fact the compiler lets this slip is historical).
So I did

const char *p = new char[6];

But then how do I initialize it to "Hello"? My requirement is - I want
a const char* initialised and later want to modify the contents.

Yoj can't initalialize it, but you can copy into it.
strcpy(p, "hello");
I know a way as written below

const char p[] = "hello";
const_cast<char&>(p[0]) = 'K'; //OK

But how to acheive this with pointers?

What I know is - C compiler allocates memory when I do
const char* = "hello";

But C++ compiler does not do that. Any help is welcome.
Nope, C and C++ actually behave identically in this aspect.
 
P

Pete C

Firstly, and most importantly, in C++ you should be using std::string
to do this kind of stuff. This is especially true if you are having
difficulty with pointers and memory management, as you appear to.

S said:
const char *p = "Hello";

So, here memory is not allocated by C++ compiler for p and hence I
cannot access p[0] to modify the contents to "Kello"
p[0] = 'K'; // error at runtime

That's an arror at compile time, not runtime. You can't modify p[0] is
because p is a pointer to a const char.
But then how do I initialize it to "Hello"? My requirement is - I want
a const char* initialised and later want to modify the contents.

I know a way as written below

const char p[] = "hello";
const_cast<char&>(p[0]) = 'K'; //OK

That's not OK, that's very bad. If the program appeared to work, it's
only because you were unlucky. If you use const_cast to modify
something that is actually const then you get Undefined Behaviour
(which seems to be considered one of the 4 horsemen of the apocalypse
around these parts). In any case, don't do it.
But how to acheive this with pointers?

A couple of ways:

char *p = new char[6];
strncpy(p, "hello", 6);
const char *q = p; // if you really need a const char*
p[0] = 'K';
delete [] p;

or

char p[] = "hello";
const char *q = p; // if you really need a const char*
p[0] = 'K';

But you would be better off with:

std::string hello = "hello";
hello[0] = 'K';

much cleaner, much safer.
 
T

toton

S said:
Hi Everyone

I have

const char *p = "Hello";

So, here memory is not allocated by C++ compiler for p and hence I
cannot access p[0] to modify the contents to "Kello"
p[0] = 'K'; // error at runtime

So I did

const char *p = new char[6]; Why you did so?
But then how do I initialize it to "Hello"? My requirement is - I want
a const char* initialised and later want to modify the contents.
Why you want to make it const char* when you are going to modify it? If
you want some function to prevent from modifying it, write const char*
in the function signature. It will convert char* to const char*. const
char* (or any other const data member pointer) should be used when you
dont want it to change. Under very special cases, const_cast can be
used to remove const-ness, and don't make it a habit. If you need to
change the data, simply dont use const , and better use std::string
instead of char* .
I know a way as written below

const char p[] = "hello";
const_cast<char&>(p[0]) = 'K'; //OK

But how to acheive this with pointers?

What I know is - C compiler allocates memory when I do
const char* = "hello";

But C++ compiler does not do that. Any help is welcome.
Neither C do it. None of them allocate memory for pointer. However both
do for the string.
 
S

S S

S said:
Hi Everyone

I have

const char *p = "Hello";

So, here memory is not allocated by C++ compiler for p and hence I
cannot access p[0] to modify the contents to "Kello"
p[0] = 'K'; // error at runtime

So I did

const char *p = new char[6];

But then how do I initialize it to "Hello"? My requirement is - I want
a const char* initialised and later want to modify the contents.

I know a way as written below

const char p[] = "hello";
const_cast<char&>(p[0]) = 'K'; //OK

But how to acheive this with pointers?

What I know is - C compiler allocates memory when I do
const char* = "hello";

But C++ compiler does not do that. Any help is welcome.

Thanks
SS

I am sorry, please read my first line as
char * p = "hello";
in my previous mail

But I am able to get the desired result by the following way , but I am
amazed how it has worked?

const char* ptrc = new char[6];
memcpy(const_cast<char*>(ptrc),"hello",6);
//memcpy((char*)ptrc,"hello",6); // this also works
printf("%s\n",ptrc); // hello
const_cast<char&>(ptrc[0]) = 'K'; //Kello

My question is "How I am able to modify the constness of memory by
using 2nd statement which actually is supposed to remove the constness
of pointers only???
Is my compiler wrong?

Thanks
SS
 
S

S S

Ron said:
S said:
const char *p = "Hello";

So, here memory is not allocated by C++ compiler for p and hence I
cannot access p[0] to modify the contents to "Kello"
p[0] = 'K'; // error at runtime

No, that is not correct. First, you need to understand two things.
P is a pointer. It is a variable that holds the address of a char.
The memory for p itself is allocated in the context it was declared
(most likely local to a the function that contains it).

"Hello" in this context is allocated by the implementation at some
unspecified location as a array of (const) chars, this value is
converted to a pointer and stored in p.

First, your error should have happened NOT at runtime. The compiler
should reject at compile time the access violation of storing into
a const char.

Even if you were not to use const here:
char* p = "Hello";
p[0] = 'K';

Actually that is what I meant , I put const there by mistake.
is undefined behavior. The string literal memory is not allowed
to be changed (the fact the compiler lets this slip is historical).

If we can not do p[0] = 'K'; in above case
then what would be the difference b/w
const char* p = "hello";
and
char* p ="hello";
both does not allow writing operation.
So I did

const char *p = new char[6];

But then how do I initialize it to "Hello"? My requirement is - I want
a const char* initialised and later want to modify the contents.

Yoj can't initalialize it, but you can copy into it.
strcpy(p, "hello");

I can not copy into it as it is const memory. I have to do typecast as
I did in one of my later mails.
I know a way as written below

const char p[] = "hello";
const_cast<char&>(p[0]) = 'K'; //OK

But how to acheive this with pointers?

What I know is - C compiler allocates memory when I do
const char* = "hello";

But C++ compiler does not do that. Any help is welcome.
Nope, C and C++ actually behave identically in this aspect.
 
S

S S

Pete said:
Firstly, and most importantly, in C++ you should be using std::string
to do this kind of stuff. This is especially true if you are having
difficulty with pointers and memory management, as you appear to.

S said:
const char *p = "Hello";

So, here memory is not allocated by C++ compiler for p and hence I
cannot access p[0] to modify the contents to "Kello"
p[0] = 'K'; // error at runtime

That's an arror at compile time, not runtime. You can't modify p[0] is
because p is a pointer to a const char.
But then how do I initialize it to "Hello"? My requirement is - I want
a const char* initialised and later want to modify the contents.

I know a way as written below

const char p[] = "hello";
const_cast<char&>(p[0]) = 'K'; //OK

That's not OK, that's very bad. If the program appeared to work, it's
only because you were unlucky. If you use const_cast to modify
something that is actually const then you get Undefined Behaviour
(which seems to be considered one of the 4 horsemen of the apocalypse
around these parts). In any case, don't do it.

I think you are wrong here, when you see sizeof(p) here you will see
the size of string which means memory is allocated here and can always
be modified. IF I can not use const_cast which is actually const then
what is purpose of const_cast then.
But how to acheive this with pointers?

A couple of ways:

char *p = new char[6];
strncpy(p, "hello", 6);
const char *q = p; // if you really need a const char*
p[0] = 'K';
delete [] p;

or

char p[] = "hello";
const char *q = p; // if you really need a const char*
p[0] = 'K';

But you would be better off with:

std::string hello = "hello";
hello[0] = 'K';

much cleaner, much safer.
 
?

=?ISO-8859-1?Q?=22Nils_O=2E_Sel=E5sdal=22?=

S said:
Ron said:
S said:
const char *p = "Hello";

So, here memory is not allocated by C++ compiler for p and hence I
cannot access p[0] to modify the contents to "Kello"
p[0] = 'K'; // error at runtime
No, that is not correct. First, you need to understand two things.
P is a pointer. It is a variable that holds the address of a char.
The memory for p itself is allocated in the context it was declared
(most likely local to a the function that contains it).

"Hello" in this context is allocated by the implementation at some
unspecified location as a array of (const) chars, this value is
converted to a pointer and stored in p.

First, your error should have happened NOT at runtime. The compiler
should reject at compile time the access violation of storing into
a const char.

Even if you were not to use const here:
char* p = "Hello";
p[0] = 'K';

Actually that is what I meant , I put const there by mistake.
is undefined behavior. The string literal memory is not allowed
to be changed (the fact the compiler lets this slip is historical).

If we can not do p[0] = 'K'; in above case
then what would be the difference b/w
const char* p = "hello";
and
char* p ="hello";
both does not allow writing operation.
One would be a compile time error, and the other might be a runtime error.

Just make a non-const array, and initialize it.
char p[] = "hello";
Or if you did want to allocate storage yourself, you need to copy
the string into it afterwards.
char *p = new char[6];
strcpy(p,"hello");

(there are better C++ ways of doing what you need to do, likely.)
 
K

Kai-Uwe Bux

S said:
Pete said:
Firstly, and most importantly, in C++ you should be using std::string
to do this kind of stuff. This is especially true if you are having
difficulty with pointers and memory management, as you appear to.

S S wrote: [snip]
But then how do I initialize it to "Hello"? My requirement is - I want
a const char* initialised and later want to modify the contents.

I know a way as written below

const char p[] = "hello";
const_cast<char&>(p[0]) = 'K'; //OK

That's not OK, that's very bad. If the program appeared to work, it's
only because you were unlucky. If you use const_cast to modify
something that is actually const then you get Undefined Behaviour
(which seems to be considered one of the 4 horsemen of the apocalypse
around these parts). In any case, don't do it.

I think you are wrong here, when you see sizeof(p) here you will see
the size of string which means memory is allocated here and can always
be modified.

Nope, he is right. 7.1.5.1/4 says:

Except that any class member declared mutable (7.1.1) can be modified, any
attempt to modify a const object during its lifetime (3.8) results in
undefined behavior.

IF I can not use const_cast which is actually const then
what is purpose of const_cast then.

The purpose is to be able to use C libraries: those functions do often take
a char* where in C++ you would use a char const*. In order to pass the
argument, you have to cast away the constness. However, the behavior is
only defined if the C function does not modify the passed char array.


Best

Kai-Uwe Bux
 
B

benben

I am sorry, please read my first line as
char * p = "hello";

Try not to do that. A string literal is of type const char*. It is
allowed for compilation just for C-compatibility.
in my previous mail

But I am able to get the desired result by the following way , but I am
amazed how it has worked?

const char* ptrc = new char[6];
memcpy(const_cast<char*>(ptrc),"hello",6);
//memcpy((char*)ptrc,"hello",6); // this also works
printf("%s\n",ptrc); // hello
const_cast<char&>(ptrc[0]) = 'K'; //Kello

If you want to modify, why put up with const in the first place?

Either do

char p[] = {'h', 'e', 'l', 'l', 'o', 0};
p[0] = 'K'; // OK

or

char* p = new char[6];

if (p != 0)
{
strcpy(p, "hello");
p[0] = 'K'; // OK
delete[] p;
}

Or even better, use std::string

std::string str = "Hello";
str[0] = 'K'; // also ok

Notice that any of the examples (especially the last one) are elegant,
and above all, correct, compared to your solutions with const_cast.
My question is "How I am able to modify the constness of memory by
using 2nd statement which actually is supposed to remove the constness
of pointers only???

Undefined Behavior means any kind of behavior can occur, which includes
what you wanted to achieve. But that's just shear luck.
Is my compiler wrong?

Nope.

Remember, const is a language level tool for you to make sure you don't
unintentionally modify something you are not meant to. If you do want to
modify it, don't make it const.
 
B

benben

[snip]
Why do you make the array const if you want to write to it? Just do:

char p[] = "hello";
p[0] = 'K';
But how to acheive this with pointers?

char p[] = "hello";
char* ptr = p;
ptr[0] = 'K';

This is not strictly correct. You are modifying the string literal
itself which is supposedly a const char*.

Generally speaking, you should always assign a string literal to a const
char[] or const char*

const char[] = "hello";
const char* = "world";

So you can't modify them.

Regards,
Ben
 
R

Rolf Magnus

benben said:
[snip]
Why do you make the array const if you want to write to it? Just do:

char p[] = "hello";
p[0] = 'K';
But how to acheive this with pointers?

char p[] = "hello";
char* ptr = p;
ptr[0] = 'K';

This is not strictly correct. You are modifying the string literal
itself which is supposedly a const char*.

No, I'm not modifying the literal, and p is not a pointer. It's an array,
and the content of the string literal is copied into that array on
initialization. Therefore, it's perfectly fine to modify it.
Generally speaking, you should always assign a string literal to a const
char[] or const char*

const char[] = "hello";
const char* = "world";

So you can't modify them.

For the second line, that's true, but not for the first one.
 
R

Rolf Magnus

S said:
So I did

const char *p = new char[6];

But then how do I initialize it to "Hello"? My requirement is - I want
a const char* initialised and later want to modify the contents.

Yoj can't initalialize it, but you can copy into it.
strcpy(p, "hello");

I can not copy into it as it is const memory. I have to do typecast as
I did in one of my later mails.

The allocacted memory itself is not const, but you access it through a
pointer to const. Leave out the 'const', and the strcpy will work without a
cast.
 
R

Rolf Magnus

S said:
But I am able to get the desired result by the following way , but I am
amazed how it has worked?

const char* ptrc = new char[6];
memcpy(const_cast<char*>(ptrc),"hello",6);
//memcpy((char*)ptrc,"hello",6); // this also works
printf("%s\n",ptrc); // hello
const_cast<char&>(ptrc[0]) = 'K'; //Kello

My question is "How I am able to modify the constness of memory by
using 2nd statement which actually is supposed to remove the constness
of pointers only???

What makes you think that the memory is const? It is not.
Is my compiler wrong?

No.
 
F

Frederick Gotham

S S posted:
const char *p = "Hello";

So, here memory is not allocated by C++ compiler for p and hence I
cannot access p[0] to modify the contents to "Kello"
p[0] = 'K'; // error at runtime

String Literals have static storage duration. Therefore, it's quite
equivalent to:

/* Step 1: We have a static duration const array. */

static char const literal_[] = {'H','e','l','l','o',0};

/* Step 2: It's appears non-const even though we're
not allowed to modify it. */

char (&literal)[sizeof literal_] =
const_cast<char(&)[sizeof literal_]>(literal_);

/* Step 3: We store its address in a pointer variable. */

char const *p = literal;

So I did

const char *p = new char[6];

But then how do I initialize it to "Hello"? My requirement is - I want
a const char* initialised and later want to modify the contents.

C++ is broken in the respect that you can't individually initialise
individual array elements (...well you can, but it involves a work-around
involving placement new). Anywho, simple assignment will suffice in the
case of POD's:

char *const p = new char[6];

p[0] = 'H';
p[1] = 'e';
p[2] = 'l';
p[3] = 'l';
p[4] = 'o';
p[5] = 0;

delete [] p;
I know a way as written below

const char p[] = "hello";
const_cast<char&>(p[0]) = 'K'; //OK


The behaviour of altering const data is not defined by the International
C++ Standard. In compiling that code, any conforming compiler is entitled
to produce a program which does absolutely anything (and yes, I mean
_anything_).

But how to acheive this with pointers?

What I know is - C compiler allocates memory when I do
const char* = "hello";

Syntax error -- it sort of looks like a definition, except there's no name
for the object. Anywho, if you want a non-const char array which contains a
null-terminated string at the point of initialisation, then maybe play
around with:

char str[] = "Hello";

Don't be fooled by the syntax -- the thing on the left is NOT a string
literal, it's just a pretty way of writing:

char str[] = {'H','e','l','l','o',0};
 
F

Frederick Gotham

benben posted:
Generally speaking, you should always assign a string literal to a const
char[] or const char*

const char[] = "hello";
const char* = "world";


That information is flawed.

The first example does NOT contain any string literal whatsoever; it's just
the syntax we use to conveniently initialise an array. The following two
definitions are exactly equivalent:

char str[] = "hello";
char str[] = {'h','e','l','l','o',0};

The second example however DOES contain a string literal. We know string
literals to be of static storage duration, so we can say it's quite
equivalent to:

static char const literal_[] = {'H','e','l','l','o',0};

char (&literal)[sizeof literal_] =
const_cast<char(&)[sizeof literal_]>(literal_);

char const *p = literal;
 
F

Frederick Gotham

Pete C posted:
char p[] = "hello";

The name of that object is misleading -- it suggests that it is a pointer
rather than an array.
But you would be better off with:

std::string hello = "hello";
hello[0] = 'K';

much cleaner, much safer.


Yes, but unfortunately it is far less efficient (but this may not be a
problem for your requirements.)
 
F

Frederick Gotham

S S posted:
I am sorry, please read my first line as
char * p = "hello";
in my previous mail


Extremely il-advised. You're storing the address of non-modifiable data in a
pointer to non-const.

But I am able to get the desired result by the following way , but I am
amazed how it has worked?

const char* ptrc = new char[6];


Here you store the address of non-const data in a pointer to const. Be
consistent! Either use:

char const *const p = new char const[6];

or:

char *const p = new char[6];

memcpy(const_cast<char*>(ptrc),"hello",6);


This behaviour of this statement is well-defined, as it does not modify const
data.

//memcpy((char*)ptrc,"hello",6); // this also works


Yes, this is equivalent.

printf("%s\n",ptrc); // hello


You're mixing C and C++ all over the place! If you're hell-bent on using C
functions in C++ code, you must change:

#include <stdio.h>

printf(...

to:

#include <cstdio>

std::printf(...

const_cast<char&>(ptrc[0]) = 'K'; //Kello


Again, the behaviour is well-defined because the data is ours to modify.

My question is "How I am able to modify the constness of memory by
using 2nd statement which actually is supposed to remove the constness
of pointers only???


Your question is flawed. The following denotes a const pointer:

char *const p;

The following two denote a pointer to const:

char const *p;
const char *p;

The following two denote a const pointer to const:

char const *const p;
const char *const p;

A "const_cast" can be used to strip away either of the constnesses (i.e.
whether the pointer itself is const, or whether the data it points to may be
modified by the pointer in question.)
Is my compiler wrong?

You'll get your head around all this soon enough. Keep asking questions until
you're absolutely certain you know what's going on -- that's what sets the
good programmers from the great programmers.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,994
Messages
2,570,222
Members
46,810
Latest member
Kassie0918

Latest Threads

Top