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 32192
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
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
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
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
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
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_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
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
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
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
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<iostre am>
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
This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
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.
...
|
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 );
|
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?
|
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)
{}
|
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)
{
| |
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;
|
by: d3x0xr |
last post by:
---- Section 1 ----
------
x.c
int main( void )
{
char **a;
char const *const *b;
b = a; // line(9)
|
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...
|
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)
{
|
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,...
|
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...
| |
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...
|
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...
|
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...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |
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...
| |