473,836 Members | 2,204 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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
42 32197
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******** *************@m 73g2000cwd.goog legroups.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_ca st<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*)p trc,"hello",6); // this also works


Yes, this is equivalent.

printf("%s\n",p trc); // 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

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

Similar topics

3
2241
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. Someone on the SuSE programming mailing list suggested my problem is that I'm trying to execute a function (I assume he meant the constructor) at compile time. The same source code compile if I don't try to split it up into separate libraries. ...
5
2166
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 * const &p ); char foo (const char * &const p ); char foo (const char &* const p ); char foo (const &char * const p );
7
4370
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 type of "const char *". Right? But why does the compiler I am using allow s to be modified, instead of generating compile error?
8
2599
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. char * -> const char *. However, this does not appear to work when I add another level of indirection: void test1 (char **value) {}
6
10059
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 hoped I could solve, and I couldn't. Some code he's using, written in 1999, that compiled fine in 1999, no longer does in 2006 with g++ 4. This little bit of code: SimS::SimS (ostream &s) {
10
5327
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
2798
by: d3x0xr | last post by:
---- Section 1 ---- ------ x.c int main( void ) { char **a; char const *const *b; b = a; // line(9)
0
1879
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, and you'll be left with just noisy compiler warnings and confusion. if you start a project with all char *, and char ** and even char ***, if you begin at the low level weeding out references of 'passing const char * to char * ( such as...
9
10534
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 strspcmp(const char * s1, const char * s2) {
0
9810
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, well explore What is ONU, What Is Router, ONU & Routers main usage, and What is the difference between ONU and Router. Lets take a closer look ! Part I. Meaning of...
0
9656
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10821
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10527
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10573
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10241
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7773
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupr who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
2
4001
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3102
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.