Converting const char * to char * [SOLVED] - DaniWeb
文章推薦指數: 80 %
>Is there a way to convert from const char * >to char * without casting away the const? Short answer: No. >I was warned that it could be ... Convertingconstchar*tochar* Home ProgrammingForum SoftwareDevelopmentForum Discussion/Question Isthereawaytoconvertfromconstchar*tochar*withoutcastingawaytheconst?Iwaswarnedthatitcouldbedangerousandcausecrashes(whichIwouldagreewith,sincewhenIranmyprogramwithconst_cast,itcausedasegmentationfault).Alternatively,isthereawaytoconvertfromstringtochar*(notconvertfromstringtoconstchar*,asc_str()does)?Anysuggestionswouldbegreatlyappreciated. //Readthewordlistfile ifstreamwordlist("./samplewordlist.txt"); Dictionaryhtl; if(wordlist) { cout<(constConvline); htl.add(convline); cout<Isthereawaytoconvertfromconstchar* >tochar*withoutcastingawaytheconst? Shortanswer:No. >Iwaswarnedthatitcouldbedangerousandcausecrashes It'sconstforareason.Forexample,whenyoupointtoastringliteral,thepointershould… JumptoPost All4Replies >Isthereawaytoconvertfromconstchar* >tochar*withoutcastingawaytheconst? Shortanswer:No. >Iwaswarnedthatitcouldbedangerousandcausecrashes It'sconstforareason.Forexample,whenyoupointtoastringliteral,thepointershouldbedeclaredas"constchar*"becausestringliteralsarestoredinread-onlymemory.Castingawaytheconstwon'tchangetheread-onlynatureofthedataitself,andtryingtomodifyitwillprobablycauseacrash. Youshouldonlycastawayconstifyou'resosurethatthechamberisempty,you'dbewillingtopointthegunatyourfaceandpullthetriggerwithoutanyhesitation.Inallothercases,workaroundtheconst.Makeacopy,forexample: char*pline=newchar[line.size()+1]; strcpy(pline,line.c_str()); htl.add(pline); cout<Alternatively,isthereawaytoconvertfromstringtochar*(notconvertfromstringtoconstchar*,asc_str()does)? Yesthereis: strings1="HelloWorld"; char*s2=newchar[s1.size()+1]; strcpy(s2,s1.c_str()); deletes2; explanationofthecode: line1:declareastringandputsomesampledatainit line2:dynamicallyallocatememory(oneelementextrabecauseoftheNULL-terminator) line3:createacopyfromtheconstantstringandputitintoanon-constantcharacterarray line4:freeupdynamicallyallocatedmemory 0 0 Share Narue, Thankyousomuchforexplainingthattome!Itwasreallyhelpful.Also,IwassuperexcitedwhenIsawthatyourhomepagewaseternallyconfuzzledbecauseIsawitbeforeandbookmarkedit!Theinternet(thatdiscussesC++)isasmallworld:3 0 0 Share tux4life, Thanksalotforprovidingyourexplanation!ItreallyhelpedandIreallyappreciateit! 0 0 Share Facebook Like Twitter Tweet BeapartoftheDaniWebcommunity We'reafriendly,industry-focusedcommunityofdevelopers,ITpros,digitalmarketers, andtechnologyenthusiastsmeeting,learning,andsharingknowledge. SignUp—It'sFree! RelatedTopics ConvertingaBSTRtochar*(inC++) 1 convertingbool[8]tochar 5 ATorATXcommandsusingc 6 DynamicMemory,Alternatetousingchar*c=newchar[10] 4 ConvertingaPythonProgrammetoC++ 2 CreatingLogin 22 CharprobleminC++Calculator 2 typecastchar*tochar 3 sms-chatapplicationinvb.net(urgenthelpneeded) 3 ConvertchartodoubleC++ 4 Howtoreadafilecharbycharandreplaceitwithstring???? 3 whatiswrongwiththiscodesnippet-memset()implementation 2 lifeofvariablesinc++functions 3 Stringtochar*conversion 9 ErrorinCreatematerilsTable 5 Can'tsprintfconstchar? 2 Confusedaboutuse*indeclaringchararrays 7 writingaloopwithlettersnotnumbers 7 c++dynamicchararray 4 C++StringParsing? 3 Notwhatyouneed? Reachouttoalltheawesomepeopleinoursoftwaredevelopmentcommunitybystartingyourowntopic. Weequallywelcomebothspecificquestionsaswellasopen-endeddiscussions. StartNewTopic TopicsFeed ReplytothisTopic Thisquestionhasalreadybeensolved! Thepersonwhoaskedthisquestionhasmarkeditassolved. Solvedquestionsliveforeverinourknowledgebasewheretheygoontohelpothersfacingthesameissuesforyearstocome. Areyousureyouhavesomethingvaluabletoaddthathasnotalreadybeenmentioned? Considerstartinganewtopicinstead. Otherwise,pleasebethoughtful,detailedandcourteous,andadheretoourpostingrules. Edit Preview Message H1 H2 PostReply BrokenLink You'retryingtovisitaURLthatdoesn'tcurrentlyexistontheweb. Mostlikely,amemberpostedalinkalongtimeagotoawebpagethathassincebeenremoved. It'salsopossiblethattherewasatypowhenpostingtheURL. Weredirectyoutothisnoticeinsteadofstrippingoutthelinktopreservetheintegrityofthepost. GoBacktothePost ContinueAnyways SharePost PermanentLink Facebook Like Twitter Tweet InsertCodeBlock InsertCodeBlock Search Search ForumCategories Hardware/Software Programming DigitalMedia CommunityCenter LatestContent NewestTopics LatestTopics LatestPosts TopTags TopicsFeed Social TopMembers CommunityFunctions DaniWebPremium NewsletterArchive MarkdownSyntax CommunityRules DeveloperAPIs ConnectAPI ForumAPIDocs Legal TermsofService PrivacyPolicy FAQ AboutUs Advertise ContactUs ©2022DaniWeb®LLC
延伸文章資訊
- 1Converting const char * to char * [SOLVED] - DaniWeb
>Is there a way to convert from const char * >to char * without casting away the const? Short ans...
- 2const char*, char const*, char*const 的区别 - 菜鸟教程
Bjarne在他的The C++ Programming Language里面给出过一个助记的方法:把一个声明从右向左读。 char * const cp; ( * 读成pointer to )...
- 3Difference between const char* p, char * const ... - Tutorialspoint
const char* const says that the pointer can point to a constant char and value of int pointed by ...
- 4Difference between const char *p, char * const p and const ...
1. const char *ptr : This is a pointer to a constant character. You cannot change the value point...
- 5How to convert const char* to char* in C? - Stack Overflow
First of all you should do such things only if it is really necessary - e.g. to use some old-styl...