How to convert const char* to char* in C? - Stack Overflow

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

First of all you should do such things only if it is really necessary - e.g. to use some old-style API with char* arguments which are not ... Resultsfromthe2022DeveloperSurveyarenowavailable Home Public Questions Tags Users Companies Collectives ExploreCollectives Teams StackOverflowforTeams –Startcollaboratingandsharingorganizationalknowledge. CreateafreeTeam WhyTeams? Teams CreatefreeTeam Collectives™onStackOverflow Findcentralized,trustedcontentandcollaboratearoundthetechnologiesyouusemost. Learnmore Teams Q&Aforwork Connectandshareknowledgewithinasinglelocationthatisstructuredandeasytosearch. Learnmore Howtoconvertconstchar*tochar*inC? AskQuestion Asked 7years,10monthsago Modified 1year,9monthsago Viewed 226ktimes 81 16 Inmyprojectthereisamethodwhichonlyreturnsaconstchar*,whereasIneedachar*string,astheAPIdoesn'tacceptconstchar*. Anyideahowtoconvertbetweenconstchar*tochar*? cpointersconst-char Share Follow editedMar11,2016at14:07 nbro 13.9k2525goldbadges9999silverbadges185185bronzebadges askedAug28,2014at13:06 MorpheusMorpheus 2,99533goldbadges2525silverbadges5151bronzebadges 7 9 BewarethattheAPImighthavebeendesignthiswaywithgoodreasonsinmind. – alk Aug28,2014at13:08 1 @alkI'dsaidthisbelowandthisisthesituation:Theconstchar*isreturnedbyanobjective-Cstringmethod[NSString'stobemorespecific).Thisisapathofafilewhichgotsaved.NowthereisanotherClibrary'sapiwhichwillbeparsingthisfileanditonlytakeschar*stringsasarguments.Evenifipasstheconstchar*string,theparsinghappensbutigetawarningwhichidon'twanttosee. – Morpheus Aug28,2014at13:33 Asotherspointedout:Asyouneverknowwhattheparserdoes(thinkofwhatstrtok()does)makeacopyofthedatareturnedandpassonthecopy.strdup()andfree()areyourfriends. – alk Aug28,2014at13:42 1 Canyoutelluswhichfunctionstheyareandlinktotheirdocumentation? – mafso Aug28,2014at13:44 2 AndinC++thereisconst_cast<>() – Kotauskas Jun7,2019at15:43  |  Show2morecomments 6Answers 6 Sortedby: Resettodefault Highestscore(default) Trending(recentvotescountmore) Datemodified(newestfirst) Datecreated(oldestfirst) 67 Firstofallyoushoulddosuchthingsonlyifitisreallynecessary-e.g.tousesomeold-styleAPIwithchar*argumentswhicharenotmodified.IfanAPIfunctionmodifiesthestringwhichwasconstoriginally,thenthisisunspecifiedbehaviour,verylikelycrash. Usecast: (char*)const_char_ptr Share Follow editedOct16,2018at23:54 answeredAug28,2014at13:07 WojtekSurowkaWojtekSurowka 19.7k44goldbadges4444silverbadges4949bronzebadges 6 13 Ithinkthisanswerasitisencouragestoomuchadangerouspractice.Itcouldbeimprovedbymakingthewarningsaboutundefinedbehaviourclearerandstronger.AtthemomentIthinkmanyreaderswilljustreadthefirst2linesandnotnoticetheimportantwarnings. – PeterSW Aug28,2014at15:07 3 Nowwarningsarefirstandtheanswerlater. – WojtekSurowka May13,2015at21:14 2 Oratleastuseconst_castsothecompilerknowstoo. – MultiMat Oct15,2018at12:29 @MultiMatNosuchthingasconst_castinC. – WojtekSurowka Oct15,2018at13:09 MyC++isrustybutwouldntthiscauseissues,whenitgoesoutofscope? – Hossein Apr14,2020at15:05  |  Show1morecomment 31 Tobesafeyoudon'tbreakstuff(forexamplewhenthesestringsarechangedinyourcodeorfurtherup),orcrashyouprogram(incasethereturnedstringwasliteralforexamplelike"helloI'maliteralstring"andyoustarttoeditit),makeacopyofthereturnedstring. Youcouldusestrdup()forthis,butreadthesmallprint.Oryoucanofcoursecreateyourownversionifit'snotthereonyourplatform. Share Follow editedSep12,2020at6:42 answeredAug28,2014at13:08 meaning-mattersmeaning-matters 20k99goldbadges7676silverbadges125125bronzebadges 2 4 Necroforaresponsetothequestioncan'tyouchangeyourcode:APIsoftenrequirestring,char*orconstchar*,andyeahintheoryyoucouldchangetheentireAPI,butit'sgoodinformationtoknowhowtoquicklyconvertit – Skathix Apr25,2018at17:44 @SkathixYou'reright,APIscan'toftenbechanged(Ithinkwrotethatinerror).Removedthatpartofmyanswer.Thanks! – meaning-matters Sep12,2020at6:43 Addacomment  |  29 Youcanusethestrdupfunctionwhichhasthefollowingprototype char*strdup(constchar*s1); Exampleofuse: #include char*my_str=strdup("Mystringliteral!"); char*my_other_str=strdup(some_const_str); orstrcpy/strncpytoyourbuffer orrewriteyourfunctionstouseconstchar*asparameterinsteadofchar*wherepossiblesoyoucanpreservetheconst Share Follow editedMar15,2016at19:14 answeredAug28,2014at13:11 j123b567j123b567 2,79911goldbadge2020silverbadges2828bronzebadges 5 3 strdupisanonstandardimplemantation.Soyoushouldn'tbesurehe"canuseit" – dhein Aug28,2014at13:13 Implementingamissingstrdup()isamatterof15minutes. – alk Aug28,2014at13:44 5 @alkofcourse.ButastheOPiscatchingsuchaproblemandisaskingforasolution,itisposibblynotasolutionforhim"implementingstrdupbyyourself"yaknow? – dhein Aug28,2014at14:15 @Zaibis:if(constptr){char*p=calloc(strlen(constptr)+1,sizeof(*constptr));if(!p)fail();strcpy(p,constptr);my_nonconstptr_func(p);free(p);} – alk Aug28,2014at14:19 2 @alkwell,nowwehavetheimplementation.Doesn'tchangeanythingonmystatement.;) – dhein Aug28,2014at14:21 Addacomment  |  7 Aconsttoapointerindicatesa"read-only"memorylocation.Whereastheoneswithoutconstarearead-writememoryareas.So,you"cannot"convertaconst(read-onlylocation)toanormal(read-write)location. Thealternateistocopythedatatoadifferentread-writelocationandpassthispointertotherequiredfunction.Youmayusestrdup()toperformthisaction. Share Follow answeredAug28,2014at13:17 raghav3276raghav3276 1,03888silverbadges1414bronzebadges 1 1 Exactly.constisspecifiedtosaythatthevalueremainsconstantandcannotbefurthermodified. – AditYa Nov25,2016at9:37 Addacomment  |  2 Toconvertaconstchar*tochar*youcouldcreateafunctionlikethis: #include #include #include char*unconstchar(constchar*s){ if(!s) returnNULL; inti; char*res=NULL; res=(char*)malloc(strlen(s)+1); if(!res){ fprintf(stderr,"MemoryAllocationFailed!Exiting...\n"); exit(EXIT_FAILURE); }else{ for(i=0;s[i]!='\0';i++){ res[i]=s[i]; } res[i]='\0'; returnres; } } intmain(){ constchar*s="thisisbikash"; char*p=unconstchar(s); printf("%s",p); free(p); } Share Follow editedJul3,2020at9:04 answeredApr17,2019at2:31 BikashBikash 13266bronzebadges 2 1 Inthiscodeuninitializedvariableresisused.Thiscoderes[i]=s[i]isundefinedbehavior,mostlikelycrash. – WojtekSurowka Jun5,2020at9:02 UpdatedCode:AddedcheckforNULLandpossiblyresolvedundefinedbehavior. – Bikash Jul3,2020at9:06 Addacomment  |  1 Youcancastitbydoing(char*)Identifier_Of_Const_char Butasthereisprobabblyareasonthattheapidoesn'tacceptconstcahr*, youshoulddothisonly,ifyouaresure,thefunctiondoesn'ttrytoassignanyvalueinrangeofyourconstchar*whichyoucastedtoanonconstone. Share Follow answeredAug28,2014at13:09 dheindhein 6,14344goldbadges4141silverbadges7272bronzebadges 2 1 theconstchar*isreturnedbyanobjective-Cstringmethod[NSString'stobemorespecific).Thisisapathofafilewhichgotsaved.NowthereisanotherClibrary'sapiwhichwillbeparsingthisfileanditonlytakeschar*stringsasarguments.Evenifipasstheconstchar*string,theparsinghappensbutigetawarningwhichidon'twanttosee. – Morpheus Aug28,2014at13:31 @MorpheusAnyway,youcan'tbesureaslongyoudidn'tanalyzethesourcebyyourself. – dhein Aug28,2014at14:20 Addacomment  |  YourAnswer ThanksforcontributingananswertoStackOverflow!Pleasebesuretoanswerthequestion.Providedetailsandshareyourresearch!Butavoid…Askingforhelp,clarification,orrespondingtootheranswers.Makingstatementsbasedonopinion;backthemupwithreferencesorpersonalexperience.Tolearnmore,seeourtipsonwritinggreatanswers. Draftsaved Draftdiscarded Signuporlogin SignupusingGoogle SignupusingFacebook SignupusingEmailandPassword Submit Postasaguest Name Email Required,butnevershown PostYourAnswer Discard Byclicking“PostYourAnswer”,youagreetoourtermsofservice,privacypolicyandcookiepolicy Nottheansweryou'relookingfor?Browseotherquestionstaggedcpointersconst-charoraskyourownquestion. TheOverflowBlog Askedandanswered:theresultsforthe2022Developersurveyarehere! LivingontheEdgewithNetlify(Ep.456) FeaturedonMeta Testingnewtrafficmanagementtool AskWizardTestResultsandNextSteps Updatedbuttonstylingforvotearrows:currentlyinA/Btesting Trending:Anewanswersortingoption Visitchat Linked 31 Whyisstrdupconsideredtobeevil 0 cannotconvertargument3from'constchar[7]tochar*'invsexpress2017errorsE0289andC2664 Related 2971 Howdoyouset,clear,andtoggleasinglebit? 60 Whycan'tIconvert'char**'toa'constchar*const*'inC? 344 Whatisthedifferencebetweenchar*constandconstchar*? 1658 Whatisthedifferencebetweenconstint*,constint*const,andintconst*? 3217 ImproveINSERT-per-secondperformanceofSQLite 551 ConvertchartointinCandC++ 236 Differencebetweenchar*andconstchar*? 452 Pointersvs.valuesinparametersandreturnvalues 4 Howtoconvertproperlychar*const[256]toconstchar*const* HotNetworkQuestions FindoutvalueofpFcapacitors Formallanguagerewriterules:strangenotation RecordsgreaterthanepochtimestampusingonlyLIKEoperator InMagic,areyouallowedtorevealwhatcardsyouhavedraftedtostopothersfromdraftingthesamecolors? WhydidoldconsoleshavespecialRAMdedicatedforaspecifictask? Isthisconceptforverylowenergyspacetravelplausible? IsDaryl'sMailLegitThisTime? Howtoreplaceantidiagonalelementsofamatrix CantheEnormousTentaclesee? Whycan'tItakephotosinsideofstoresinPortugal? DoesthereexistaLatinsquareoforder9forwhichits9brokendiagonalsand9brokenantidiagonalsaretransversals? HowcanIaddalayerofmeaningtoanevilcampaign? howdoimakethiscookielookmorerealistic Drawboxesaroundnodesintikz Howareanygunrestrictionsconstitutional? Whatisthepointoftermlifeinsurance? WhyismydatanotnormallydistributedwhileIhaveanalmostperfectQQplotandhistogram? HowdoIsetvaluenodeto#frameusingpython Expectedvalueof100briefcaseseachwith1dollarexceptfor1thatresetsyouraccumulatedamounttozero? Doestheemailsizelimitincludethesizeofthebody? WhydoIgetaccostedfortakingphotosofawarmemorial? Whatisthenameofthiscreature? Checkamushroomforest Whatisthemeaningof"payinginbuttons"? morehotquestions Questionfeed SubscribetoRSS Questionfeed TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader. lang-c Yourprivacy Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy. Acceptallcookies Customizesettings  



請為這篇文章評分?