943,584 Members | Top Members by Rank

Ad:
  • C++ Discussion Thread
  • Unsolved
  • Views: 30556
  • C++ RSS
Jul 25th, 2005
0

Problems casting a const char* to char*

Expand Post »
I am currently writing a C++ program that uses a external library and engine that is primarily based in C. I am attempting to load an image file and the function requires that the argument be passed as a char *szFileName.

I have the file address as a string and my attempt to convert is as follows:

std::string path("C:\\Doc.....")
then char *FileExt = path.c_str();

I continually get the error message saying that it is not possible to convert const char * to char *!

Any1 any ideas? Any help would be much appreciated!

oh and by the way ive tried casting it using static_cast
Similar Threads
Reputation Points: 10
Solved Threads: 0
Newbie Poster
ramcfloyn is offline Offline
10 posts
since Jul 2005
Jul 25th, 2005
0

Re: Problems casting a const char* to char*

The c_str() method of the std::string class returns a pointer to const char so that you can't modify the result. Unfortunately, there's no good solution, and you can thank the author of the library who didn't write const-correct code. Now, if you know that the function will not modify the string, you can use const_cast to allow the conversion:
C++ Syntax (Toggle Plain Text)
  1. char *FileExt = const_cast<char*> ( path.c_str() );
If you're not sure whether the function will modify the string or not, you have no choice but to create a C-style string copy:
C++ Syntax (Toggle Plain Text)
  1. char *FileExt = new char[path.size() + 1];
  2. std::strcpy ( FileExt, path.c_str() );
strcpy is declared in <cstring>.

>oh and by the way ive tried casting it using static_cast
static_cast doesn't remove qualifiers, which is a very good thing because you have to actively choose const_cast, and therefore can't do it by accident.
Administrator
Reputation Points: 6442
Solved Threads: 1393
Bad Cop
Narue is offline Offline
11,807 posts
since Sep 2004
Jul 25th, 2005
0

Re: Problems casting a const char* to char*

Thanks very much that seems do have done the trick! Won't know for sure though until i'm back in tomorrow!

Cheers though It's a great help cause that was the sticking point.
Reputation Points: 10
Solved Threads: 0
Newbie Poster
ramcfloyn is offline Offline
10 posts
since Jul 2005

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in C++ Forum Timeline: C++ How do you create multifile project
Next Thread in C++ Forum Timeline: backward string





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC