473,385 Members | 2,243 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

const char* = new char[6]

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

Oct 3 '06 #1
42 32088
S S wrote:
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

Oct 3 '06 #2
S S wrote:
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?
Oct 3 '06 #3
S S wrote:
>
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.
Oct 3 '06 #4
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:
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.

Oct 3 '06 #5

S S wrote:
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.
Thanks
SS
Oct 3 '06 #6
S S

S S wrote:
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

Oct 3 '06 #7
S S

Ron Natalie wrote:
S S wrote:

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.
Oct 3 '06 #8
S S

Pete C wrote:
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:
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.
Oct 3 '06 #9
S S wrote:
Ron Natalie wrote:
>S S wrote:
>>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.)
Oct 3 '06 #10
S S wrote:
>
Pete C wrote:
>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
Oct 3 '06 #11
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.
>
Thanks
SS
Oct 3 '06 #12
[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
Oct 3 '06 #13
benben wrote:
[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.

Oct 3 '06 #14
S S wrote:
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.

Oct 3 '06 #15
S S wrote:
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.

Oct 3 '06 #16
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};

--

Frederick Gotham
Oct 3 '06 #17
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;

--

Frederick Gotham
Oct 3 '06 #18
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.)

--

Frederick Gotham
Oct 3 '06 #19
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.

--

Frederick Gotham
Oct 3 '06 #20
benben posted:
>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*.

Incorrect. The type of "Hello" is: char[sizeof"Hello"]

It is an array, not a pointer.

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];

I would advocate defining "p" as const, because we don't want its value to
change until we call "delete".

char *const p = new char[6];

--

Frederick Gotham
Oct 3 '06 #21
Frederick Gotham posted:
char str[] = "Hello";

Don't be fooled by the syntax -- the thing on the left is NOT a string
literal
Should have written "thing on the right", not left.

--

Frederick Gotham
Oct 3 '06 #22
S S wrote:
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.
Your deduction is wrong. It's true that the literal gets copied over to the
array p, and so the above code doesn't write to the literal, but you
defined the array as const, and modifying an object that was initially
defined const results in undefined behavior.
IF I can not use const_cast which is actually const then what is purpose
of const_cast then.
It's often used to deal with erroneous code that wants a pointer or
reference to an object and doesn't modify it, but fails to declare it
const.

Oct 3 '06 #23
Frederick Gotham wrote:
benben posted:
>>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*.


Incorrect. The type of "Hello" is: char[sizeof"Hello"]
That's incorrect too. "Hello" is const.

Oct 3 '06 #24
Rolf Magnus posted:
>Incorrect. The type of "Hello" is: char[sizeof"Hello"]

That's incorrect too. "Hello" is const.

Incorrect. Your compiler is non-conforming if it refuses to compile the
following when in International Standard C++ mode:

void Func(char*){}

int main() { Func("Hello"); }

You would be correct to think that the altering of a string literal produces
undefined behaviour, but nonetheless, string literals are not const.

--

Frederick Gotham
Oct 3 '06 #25
"S S" <sa***********@gmail.comwrote in message
news:11*********************@m73g2000cwd.googlegro ups.com...
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.
The right way to this is:

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

When you want to modify the contents of the memory, use q.
Oct 3 '06 #26
Frederick Gotham wrote:
Rolf Magnus posted:
>>Incorrect. The type of "Hello" is: char[sizeof"Hello"]

That's incorrect too. "Hello" is const.


Incorrect.
No, it's not.
Your compiler is non-conforming if it refuses to compile the
following when in International Standard C++ mode:

void Func(char*){}

int main() { Func("Hello"); }
That's right, but for another reason. For backwards compatiblilty with C, an
implicit conversion of a string literal to char* is allowed.
You would be correct to think that the altering of a string literal
produces undefined behaviour, but nonetheless, string literals are not
const.
I'll answer that with a quote from the standard:

2.13.4 String literals

[...]
An ordinary string literal has type “array of n const char” and static
storage duration (3.7), where n is the size of the string as defined
below, and is initialized with the given characters.

Oct 3 '06 #27
S S

Frederick Gotham wrote:
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];

Thanks for above piece of advise.
memcpy(const_cast<char*>(ptrc),"hello",6);


This behaviour of this statement is well-defined, as it does not modify const
data.
Yes, but it would have been undefined if I would have written
char const *p = new char const[6]; //here , let p be non const pointer
, here I satisfy the condition, lhs and rhs are consistent
>
//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.)
Thanks again. Can you please give 2 syntaxes in the given context where
we strip away constness
1- for pointer itself is const
2- data is const
3- both
I want to know what you have in mind when you say const_cast can be
used to remove both constness.
Thanks in advance
>
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.

--

Frederick Gotham
Oct 3 '06 #28
S S

Frederick Gotham wrote:
Rolf Magnus posted:
Incorrect. The type of "Hello" is: char[sizeof"Hello"]
That's incorrect too. "Hello" is const.


Incorrect. Your compiler is non-conforming if it refuses to compile the
following when in International Standard C++ mode:

void Func(char*){}

int main() { Func("Hello"); }
Incorrect, type of "hello" is const char[]
that can be confirmed when you overload the function
void func(char* str); //1st fxn
void func(const char* str); //2nd fxn
func("hello"); // calls the 2nd fxn
>
You would be correct to think that the altering of a string literal produces
undefined behaviour, but nonetheless, string literals are not const.

--

Frederick Gotham
Oct 3 '06 #29
Rolf Magnus posted:
>You would be correct to think that the altering of a string literal
produces undefined behaviour, but nonetheless, string literals are not
const.

I'll answer that with a quote from the standard:

2.13.4 String literals

[...]
An ordinary string literal has type “array of n const char” and
static storage duration (3.7), where n is the size of the string as
defined below, and is initialized with the given characters.

I stand corrected.

void Func(char (&str)[6]) {}

int main()
{
Func("Hello"); /* Compile ERROR */
}

--

Frederick Gotham
Oct 3 '06 #30
S S posted:
>This behaviour of this statement is well-defined, as it does not modify
const data.

Yes, but it would have been undefined if I would have written
char const *p = new char const[6];

You are correct.

Can you please give 2 syntaxes in the given context where
we strip away constness

First of all, let's start off with guinea pig: a const pointer to a const
int:

int const *const p;
const int *const p; /* These two are the same */

1- for pointer itself is const

This would only make sense if you want to yield an L-value, so I will cast
to a reference type. (Unless you cast to a reference type, a cast always
yields an R-value in C++.)

const_cast<int const*&>(p)

2- data is const

To yield an R-value: const_cast<int*>(p)

or,

To yield an L-value: const_cast<int*const&>(p)

(Not that I didn't write const_cast<int*constfor the first one -- reason
being that it would have been redundant because the cast yields an R-
value.)

3- both
Yield an L-value:

const_cast<int*&>(p)

--

Frederick Gotham
Oct 3 '06 #31
S S posted:
Incorrect, type of "hello" is const char[]
that can be confirmed when you overload the function
void func(char* str); //1st fxn
void func(const char* str); //2nd fxn
func("hello"); // calls the 2nd fxn
That is indeed quite a funky example... I've got a question for comp.std.c++.

--

Frederick Gotham
Oct 3 '06 #32
S S

Frederick Gotham wrote:
S S posted:
This behaviour of this statement is well-defined, as it does not modify
const data.
Yes, but it would have been undefined if I would have written
char const *p = new char const[6];


You are correct.

Can you please give 2 syntaxes in the given context where
we strip away constness


First of all, let's start off with guinea pig: a const pointer to a const
int:

int const *const p;
const int *const p; /* These two are the same */

1- for pointer itself is const


This would only make sense if you want to yield an L-value, so I will cast
to a reference type. (Unless you cast to a reference type, a cast always
yields an R-value in C++.)

const_cast<int const*&>(p)

2- data is const


To yield an R-value: const_cast<int*>(p)

or,

To yield an L-value: const_cast<int*const&>(p)

(Not that I didn't write const_cast<int*constfor the first one -- reason
being that it would have been redundant because the cast yields an R-
value.)

3- both

Yield an L-value:

const_cast<int*&>(p)
Bingo!!!
Thanks for explanation, that is what I was most confused about.

--

Frederick Gotham
Oct 3 '06 #33
benben schrieb:
Either do

char p[] = {'h', 'e', 'l', 'l', 'o', 0};
p[0] = 'K'; // OK
Same as this (which is shorter & easier to read):
char p[] = "hello";
p[0] = 'K';
or

char* p = new char[6];

if (p != 0)
{
No need to check the pointer. It can't be null here.
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.
If the OP wants a constant string:

const std::string str = "Hello";

He should start using the C++ features (strings and IO-streams) and come
back to plain array and pointers only when he really needs the better
performance.

--
Thomas
http://www.netmeister.org/news/learn2quote.html
Oct 3 '06 #34
S S

Frederick Gotham wrote:
Rolf Magnus posted:
You would be correct to think that the altering of a string literal
produces undefined behaviour, but nonetheless, string literals are not
const.
I'll answer that with a quote from the standard:

2.13.4 String literals

[...]
An ordinary string literal has type "array of n const char" and
static storage duration (3.7), where n is the size of the string as
defined below, and is initialized with the given characters.


I stand corrected.

void Func(char (&str)[6]) {}
Put const and compile error will go away
void Func(const char (&str)[6]) {}
I did not get what you actually wanted to say here.
>
int main()
{
Func("Hello"); /* Compile ERROR */
}

--

Frederick Gotham
Oct 4 '06 #35
S S

Frederick Gotham wrote:
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];
This is not compiling, saying uninitialized const in `new' of `const
char'
How to initialize it
If I give
char const *const p = new char const[6]("hello");
It compiles fine but if I try to print p, it does not show value hello,
jus blank line
Any idea Frederick?
>
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.

--

Frederick Gotham
Oct 4 '06 #36
S S wrote:
>
Frederick Gotham wrote:
>Rolf Magnus posted:
>You would be correct to think that the altering of a string literal
produces undefined behaviour, but nonetheless, string literals are not
const.

I'll answer that with a quote from the standard:

2.13.4 String literals

[...]
An ordinary string literal has type "array of n const char" and
static storage duration (3.7), where n is the size of the string as
defined below, and is initialized with the given characters.


I stand corrected.

void Func(char (&str)[6]) {}

Put const and compile error will go away
Yes. That was the point.
void Func(const char (&str)[6]) {}
I did not get what you actually wanted to say here.
He wanted to say that string literals are const. The fact that the above
fails without const proves it.
> int main()
{
Func("Hello"); /* Compile ERROR */
}

--

Frederick Gotham
Oct 4 '06 #37
S S posted:
> char const *const p = new char const[6];

This is not compiling, saying uninitialized const in `new' of `const
char' How to initialize it If I give char const *const p = new char
const[6]("hello"); It compiles fine but if I try to print p, it does not
show value hello, jus blank line Any idea Frederick?

Wups, you're right, you must initialise a const object:

int main()
{
int const i; /* Compile ERROR */
}

The only way in which you can initialise an array when using new is to
default-initialise it, which is done as follows:

int *p = new int[3]();

If you stick anything inside those brackets, you've got a syntax error. If
your compiler allows it, then it's either broken or possibly has some sort
of non-Standard extension enabled.

Please do more snipping in future when replying.

--

Frederick Gotham
Oct 4 '06 #38
S S

Frederick Gotham wrote:
S S posted:
char const *const p = new char const[6];
This is not compiling, saying uninitialized const in `new' of `const
char' How to initialize it If I give char const *const p = new char
const[6]("hello"); It compiles fine but if I try to print p, it does not
show value hello, jus blank line Any idea Frederick?


Wups, you're right, you must initialise a const object:

int main()
{
int const i; /* Compile ERROR */
}

The only way in which you can initialise an array when using new is to
default-initialise it, which is done as follows:

int *p = new int[3]();
Even if you do not put brackets () and write
int *p = new int[3];
then also it does the default initialisation for all 3 members of
array, any significance of brackets?
Thanks
>
If you stick anything inside those brackets, you've got a syntax error. If
your compiler allows it, then it's either broken or possibly has some sort
of non-Standard extension enabled.

Please do more snipping in future when replying.

--

Frederick Gotham
Oct 5 '06 #39
S S

Frederick Gotham wrote:
S S posted:
char const *const p = new char const[6];
This is not compiling, saying uninitialized const in `new' of `const
char' How to initialize it If I give char const *const p = new char
const[6]("hello"); It compiles fine but if I try to print p, it does not
show value hello, jus blank line Any idea Frederick?


Wups, you're right, you must initialise a const object:

int main()
{
int const i; /* Compile ERROR */
}

The only way in which you can initialise an array when using new is to
default-initialise it, which is done as follows:

int *p = new int[3]();

If you stick anything inside those brackets, you've got a syntax error. If
your compiler allows it, then it's either broken or possibly has some sort
of non-Standard extension enabled.
You are wrong here
If we stick inside those brackets, the corrosponding ctor will be
called. Example is pasted below.
#include<iostream>

class A {
public:
A() {a = 10;}
A(int b) {a = b;}
void dis() const { printf("%d\n",a);}
private:
int a;
};

int main()
{
A const* p = new A const[3](5); // not a default ctor
p->dis();
(p+1)->dis();
(p+2)->dis();
(*p).dis();
(*(p+1)).dis();
(*(p+2)).dis();
p[0].dis();
p[1].dis();
p[2].dis();
return 0;
}

Output will be
5
5
5
5
5
5
5
5
5
>
Please do more snipping in future when replying.

--

Frederick Gotham
Oct 5 '06 #40
S S posted:
A const* p = new A const[3](5);

What compiler are you using? G++ gives:

ISO C++ forbids initialization in array new
--

Frederick Gotham
Oct 5 '06 #41
S S posted:
Even if you do not put brackets () and write
int *p = new int[3];
then also it does the default initialisation for all 3 members of
array, any significance of brackets?

The Standard provides no such guarantee (well I'm 99% that it doesn't) --
if you want each element to be default-initialised, you'll have to use the
empty parentheses.

Testing it will do you no good, as I know of at least one implementation
that default-initialises new'ed memory regardless of whether you provide
the empty parentheses.

Anyhow, even if the empty parentheses were redundant, I would still put
them in, just as how I write:

int main()
{
static MyPOD arr[5] = {};
}

instead of:

int main()
{
static MyPOD arr[5];
}

Indeed, the chain brackets are redundant because static data always gets
default initialised... but nonetheless, they express clear intent.

--

Frederick Gotham
Oct 5 '06 #42

S S wrote:
Frederick Gotham wrote:
int *p = new int[3]();

Even if you do not put brackets () and write
int *p = new int[3];
then also it does the default initialisation for all 3 members of
array, any significance of brackets?
You are mistaken. No initialization occurs if the parens are not
there. Not even default initialization.

Oct 5 '06 #43

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: Steven T. Hatton | last post by:
Sorry about the big code dump. I tried to get it down to the minimum required to demonstrate the problem. Although this is all done with GNU, I believe the problem I'm having may be more general. ...
5
by: TechCrazy | last post by:
What do each of these mean? Thanks. I am incredibly confused. char foo (const char * &p ); char foo (const char &* p ); char foo (const &char * p ); char foo (const char...
7
by: al | last post by:
char s = "This string literal"; or char *s= "This string literal"; Both define a string literal. Both suppose to be read-only and not to be modified according to Standard. And both have...
8
by: Roger Leigh | last post by:
-----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 A lot of functions use const pointer arguments. If I have a non-const pointer, it is transparently made const when I pass it to the function, e.g....
6
by: Geoffrey S. Knauth | last post by:
It's been a while since I programmed in C++, and the language sure has changed. Usually I can figure out why something no longer compiles, but this time I'm stumped. A friend has a problem he...
10
by: dwaach | last post by:
Hi, I am trying to compile the following program, #include <iostream> using namespace std; typedef char* CHAR; typedef const CHAR CCHAR;
10
by: d3x0xr | last post by:
---- Section 1 ---- ------ x.c int main( void ) { char **a; char const *const *b; b = a; // line(9)
0
by: d3x0xr | last post by:
Heh, spelled out in black and white even :) Const is useles... do NOT follow the path of considering any data consatant, because in time, you will have references to it that C does not handle,...
9
by: Peithon | last post by:
Hi, This is a very simple question but I couldn't find it in your FAQ. I'm using VC++ and compiling a C program, using the /TC flag. I've got a function for comparing two strings int...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.