473,890 Members | 2,051 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 32209
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_ca st<char*>(ptrc) ,"hello",6);
//memcpy((char*)p trc,"hello",6); // this also works
printf("%s\n",p trc); // 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_ca st<char*>(ptrc) ,"hello",6);
//memcpy((char*)p trc,"hello",6); // this also works
printf("%s\n",p trc); // 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_ca st<char*>(ptrc) ,"hello",6);

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

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

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

Similar topics

3
2242
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
4374
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
2601
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
10062
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
5333
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
2804
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
10540
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
9970
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, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9810
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
11207
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...
1
10896
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
10443
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...
0
9612
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6031
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
4251
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3259
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.