const char* = new char[6]

F

Frederick Gotham

benben posted:
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];
 
F

Frederick Gotham

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.
 
R

Rolf Magnus

S said:
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.
 
F

Frederick Gotham

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.
 
A

Andrew Koenig

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.
 
R

Rolf Magnus

Frederick said:
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.
 
S

S S

Frederick said:
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.
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
 
S

S S

Frederick said:
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
 
F

Frederick Gotham

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 */
}
 
F

Frederick Gotham

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++.)

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*const> for the first one -- reason
being that it would have been redundant because the cast yields an R-
value.)


Yield an L-value:

const_cast<int*&>(p)
 
F

Frederick Gotham

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++.
 
S

S S

Frederick said:
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++.)

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*const> for the first one -- reason
being that it would have been redundant because the cast yields an R-
value.)


Yield an L-value:

const_cast<int*&>(p)

Bingo!!!
Thanks for explanation, that is what I was most confused about.

 
T

Thomas J. Gritzan

benben said:
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.
 
S

S S

Frederick said:
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.
 
S

S S

Frederick said:
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.
 
R

Rolf Magnus

S said:
Frederick said:
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.
 
F

Frederick Gotham

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.
 
S

S S

Frederick said:
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
 
S

S S

Frederick said:
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
 

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

No members online now.

Forum statistics

Threads
473,776
Messages
2,569,603
Members
45,199
Latest member
AnyaFlynn6

Latest Threads

Top