473,785 Members | 2,414 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 #1
42 32187
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_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???
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

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

Similar topics

3
2238
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
2165
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
4365
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
2597
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
10047
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
5324
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
2794
by: d3x0xr | last post by:
---- Section 1 ---- ------ x.c int main( void ) { char **a; char const *const *b; b = a; // line(9)
0
1876
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
10529
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
9646
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
10346
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
10096
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
9956
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
7504
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...
0
6742
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
4055
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3658
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2887
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.