473,692 Members | 2,525 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

converting a char* to a const char*

Hi:
What is best and safest way of converting a char* to a const char *? Can I
use const_cast?
Cheers
Sean.
Aug 6 '08 #1
35 34404
"Sean Farrow" <se*********@se anfarrow.co.ukw rites:
Hi:
What is best and safest way of converting a char* to a const char *? Can I
use const_cast?
#include <iostream>
int main(){
char* c=new char[3];

const char* cc=c; // It's that simple!

c[0]='a';c[1]='b';c[2]=0;
std::cout<<cc<< std::endl;
return(0);
}
--
__Pascal Bourguignon__
Aug 6 '08 #2
Sean Farrow wrote:
Hi:
What is best and safest way of converting a char* to a const char *? Can I
use const_cast?
No const_cast is rather technical and best not used (unless you *really*
understand what its purpose is). In a nutshell, if you have an object
that you know is not const but it appears as const via e.g a function
argument then you can use const_cast, otherwise you can't. IOW it
removes constness in the case where you know that a variable is in
memory and isnt constant, however for constants that realy are constant
it can have nasty efects. As its quite rare to know this much about what
a variable is except in private member functions and so on its rare to
need it.

regards
Andy Little
Aug 6 '08 #3
Hi:
it's a function call needing a const char*, I assume from your description,
then const_cast can be used.
Sean.
"kwikius" <an**@servocomm .freeserve.co.u kwrote in message
news:48******** **@mk-nntp-2.news.uk.tisca li.com...
Sean Farrow wrote:
>Hi:
What is best and safest way of converting a char* to a const char *? Can
I use const_cast?

No const_cast is rather technical and best not used (unless you *really*
understand what its purpose is). In a nutshell, if you have an object that
you know is not const but it appears as const via e.g a function argument
then you can use const_cast, otherwise you can't. IOW it removes constness
in the case where you know that a variable is in memory and isnt constant,
however for constants that realy are constant it can have nasty efects. As
its quite rare to know this much about what a variable is except in
private member functions and so on its rare to need it.

regards
Andy Little


Aug 6 '08 #4
Sean Farrow wrote:
What is best and safest way of converting a char* to a const char *? Can I
use const_cast?
You have got it backwards: const_cast is used to *remove* constness,
not to add it.

You don't need to do anything special to add constness to a pointer.
Anything that expects a const pointer can be given a non-const one.
Aug 6 '08 #5
Sean Farrow wrote:
it's a function call needing a const char*, I assume from your description,
then const_cast can be used.
void f( const char * );

....

void g( char * p )
{
f( p );
}
I fail to see where the problem is that you're trying to solve with
const_cast. Could you give a code example?
Aug 6 '08 #6
Hi:
I've solved the issue, it was const_cast I needed, that's going to teach me
to rad error info properly.
Thanks to everybody.
Sean.
"Juha Nieminen" <no****@thanks. invalidwrote in message
news:2q******** *****@read4.ine t.fi...
Sean Farrow wrote:
>What is best and safest way of converting a char* to a const char *? Can
I
use const_cast?

You have got it backwards: const_cast is used to *remove* constness,
not to add it.

You don't need to do anything special to add constness to a pointer.
Anything that expects a const pointer can be given a non-const one.

Aug 6 '08 #7
On 2008-08-06 10:19:42 -0400, Juha Nieminen <no****@thanks. invalidsaid:
Sean Farrow wrote:
>What is best and safest way of converting a char* to a const char *? Can I
use const_cast?

You have got it backwards: const_cast is used to *remove* constness,
not to add it.

You don't need to do anything special to add constness to a pointer.
Anything that expects a const pointer can be given a non-const one.
Not to a raw pointer, but const_cast can be used to add const in cases
where there is no implicit conversion, such as a type with multiple
levels of indirection. Granted, this is obscure (which is why i only
mention it and don't give an example). const_cast can be used to add or
remove const; in the simple cases of adding const it's not needed, so
its primary use is, as you say, to remove const.

--
Pete
Roundhouse Consulting, Ltd. (www.versatilecoding.com) Author of "The
Standard C++ Library Extensions: a Tutorial and Reference
(www.petebecker.com/tr1book)

Aug 6 '08 #8
On Aug 6, 4:19 pm, Juha Nieminen <nos...@thanks. invalidwrote:
Sean Farrow wrote:
What is best and safest way of converting a char* to a const
char *? Can I use const_cast?
You have got it backwards: const_cast is used to *remove*
constness, not to add it.
Usually. It can be used either way, and there are times when
you want to explicitly add the const, to control overload
resolution, or template instantiation, for example. Most of the
time. of course, you don't bother, since the compiler will
happily add all the consts you want, if needed.
You don't need to do anything special to add constness to a
pointer. Anything that expects a const pointer can be given a
non-const one.
For first-level const. You can't pass a char** to a function
expecting a char const**.

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

Aug 6 '08 #9
On Aug 6, 3:10*pm, "Sean Farrow" <sean.far...@se anfarrow.co.ukw rote:
Hi:
it's a function call needing a const char*, I assume from your description,
then const_cast can be used.
Nope! Dont bother with it. make a copy of the string or use
std::string.

regards
Andy Little

Aug 6 '08 #10

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

Similar topics

4
5424
by: jagmeena | last post by:
Hello, I am sure this problem has been addressed before, however, I could'nt get a suitable solution to my problem. Hence I am posting here. Thanks a lot for all your help. The code I have is typedef struct Rec { unsigned char msg; unsigned long len;
20
2167
by: Nate | last post by:
I am working on an Oakley parser and want to call an fopen function to read in the log file. I can use this to read the file, but only if I pass a "const char" variable to fopen. Since I would like the end user to specify the name of the log file, I have a scanf in there to allow the user to do so, but it isn't a const at that point. I have seen reference to calls like static_cast, dynamic_cast and reinterpret_cast in C that will allow...
7
1965
by: jamihuq | last post by:
Hello, I would like to convert the following inline function to a macro. Can someone help? Thx Jami inline char * fromDESC(const char * &aDesC)
3
2173
by: fakeprogress | last post by:
How would I go about converting this C code to C++? /* LIBRARY is an array of structures */ /* This function compares 'tcode' with */ /* existing codes in the array. */ /* It returns the index of the code in */ /* the LIBRARY structure if it is found. */ int findcode( LIBRARY *b, int n, char *tcode ) { int i;
9
30509
by: Gregory.A.Book | last post by:
I am interested in converting sets of 4 bytes to floats in C++. I have a library that reads image data and returns the data as an array of unsigned chars. The image data is stored as 4-byte floats. How can I convert the sets of 4 bytes to floats? Thanks, Greg Book
2
10906
by: pookiebearbottom | last post by:
Just looking for opinion on which of the 3 methods below people use in their code when they convert a 'const char *' to a 'const std::string &' came across #3 in someone's code and I had to think for a sec. At first I read it as converting a 'const char *' to a 'std::string *' void f(const std::string &s) { std::cout << s.size() << "\n";
11
12764
by: hamishd | last post by:
Is this possible? Sorry if this question isn't relevant here. actually, I'm really trying to convert a unsigned char * to an int
5
12643
by: Hans Mull | last post by:
Hi! How can I convert a string to a const unsigned char*? (string::c_str() converts the string to a signed char) Thanks in advance, Hans
7
4784
by: ma740988 | last post by:
Consider the equation (flight dynamics stuff): Yaw (Degrees) = Azimuth Angle(Radians) * 180 (Degrees) / 3.1415926535897932384626433832795 (Radians) There's a valid reason to use single precision floating point types. The number of decimal digits guaranteed to be correct on my implementation is 6. (i.e numeric_limits < float >::digits10 = 6 ) If I'm reading the IEEE standard, I'd could paraphrase the issue
0
8611
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
8548
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
9090
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
8813
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
8811
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
6462
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
5823
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();...
0
4564
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
1966
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.