Converting const char * to char * [SOLVED] - DaniWeb

文章推薦指數: 80 %
投票人數:10人

>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



請為這篇文章評分?