Difference between string and char[] types in C++

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

A char array is just that - an array of characters: ... A string is a class that contains a char array, but automatically manages it for you. Most ... 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 Differencebetweenstringandchar[]typesinC++ AskQuestion Asked 12years,10monthsago Modified 2years,1monthago Viewed 263ktimes 146 85 IknowalittleCandnowI'mtakingalookatC++. I'musedtochararraysfordealingwithCstrings,butwhileIlookatC++codeIseethereareexamplesusingbothstringtypeandchararrays: #include #include usingnamespacestd; intmain(){ stringmystr; cout< usingnamespacestd; intmain(){ charname[256],title[256]; cout<yougettwoheaps->memorycannotbefreed,assertionerrorsindebugmodeiflibfoomodifiesthestringreferenceandhandsanstd::stringwithanewpointerback. – Cygon Aug21,2009at20:27 2 I'mjustgoingtostickwith"Inshort:useC++stringsinallyourinternalfunctionsandmethods."TryingtounderstandyourExamplesmaidmybrainpop. – Stephen Oct29,2010at15:51  |  Show2morecomments 17 Arkaitziscorrectthatstringisamanagedtype.Whatthismeansforyouisthatyouneverhavetoworryabouthowlongthestringis,nordoyouhavetoworryaboutfreeingorreallocatingthememoryofthestring. Ontheotherhand,thechar[]notationinthecaseabovehasrestrictedthecharacterbuffertoexactly256characters.Ifyoutriedtowritemorethan256charactersintothatbuffer,atbestyouwilloverwriteothermemorythatyourprogram"owns".Atworst,youwilltrytooverwritememorythatyoudonotown,andyourOSwillkillyourprogramonthespot. Bottomline?Stringsarealotmoreprogrammerfriendly,char[]sarealotmoreefficientforthecomputer. Share Improvethisanswer Follow answeredAug17,2009at11:00 MarkRushakoffMarkRushakoff 239k4444goldbadges400400silverbadges395395bronzebadges 1 7 Atworst,otherpeoplewilloverwritememoryandrunmaliciouscodeonyourcomputer.Seealsobufferoverflow. – DavidJohnstone Mar18,2010at1:12 Addacomment  |  7 Well,stringtypeisacompletelymanagedclassforcharacterstrings,whilechar[]isstillwhatitwasinC,abytearrayrepresentingacharacterstringforyou. IntermsofAPIandstandardlibraryeverythingisimplementedintermsofstringsandnotchar[],buttherearestilllotsoffunctionsfromthelibcthatreceivechar[]soyoumayneedtouseitforthose,apartfromthatIwouldalwaysusestd::string. Intermsofefficiencyofcoursearawbufferofunmanagedmemorywillalmostalwaysbefasterforlotsofthings,buttakeinaccountcomparingstringsforexample,std::stringhasalwaysthesizetocheckitfirst,whilewithchar[]youneedtocomparecharacterbycharacter. Share Improvethisanswer Follow answeredAug17,2009at10:54 ArkaitzJimenezArkaitzJimenez 21.6k1111goldbadges7373silverbadges100100bronzebadges Addacomment  |  5 Ipersonallydonotseeanyreasonwhyonewouldliketousechar*orchar[]exceptforcompatibilitywitholdcode.std::string'snoslowerthanusingac-string,exceptthatitwillhandlere-allocationforyou.Youcansetit'ssizewhenyoucreateit,andthusavoidre-allocationifyouwant.It'sindexingoperator([])providesconstanttimeaccess(andisineverysenseofthewordtheexactsamethingasusingac-stringindexer).Usingtheatmethodgivesyouboundscheckedsafetyaswell,somethingyoudon'tgetwithc-strings,unlessyouwriteit.Yourcompilerwillmostoftenoptimizeouttheindexeruseinreleasemode.Itiseasytomessaroundwithc-strings;thingssuchasdeletevsdelete[],exceptionsafety,evenhowtoreallocateac-string. AndwhenyouhavetodealwithadvancedconceptslikehavingCOWstrings,andnon-COWforMTetc,youwillneedstd::string. Ifyouareworriedaboutcopies,aslongasyouusereferences,andconstreferenceswhereveryoucan,youwillnothaveanyoverheadduetocopies,andit'sthesamethingasyouwouldbedoingwiththec-string. Share Improvethisanswer Follow answeredAug17,2009at11:04 AbhayAbhay 6,90133goldbadges3535silverbadges4848bronzebadges 3 +1ThoughyoudidnotconsiderimplementationissueslikeDLLcompatibility,ugotCOW. – Anonymous Aug17,2009at12:35 whataboutIknowthatmychararrayin12bytes?IfIinstantiateastringforthatitmightnotbereallyefficientright? – David天宇Wong Aug16,2016at0:17 @David:Ifyouhaveextremelyperfsensitivecodethenyes.Youmightconsiderstd::stringctorcallasanoverheadinadditiontoinitializationofstd::stringmembers.ButrememberprematureoptimizationhasmadealotofcodebasesunnecessarilyC-styled,sobecareful. – Abhay Aug17,2016at14:17 Addacomment  |  2 OneofthedifferenceisNulltermination(\0). InCandC++,char*orchar[]willtakeapointertoasinglecharasaparameterandwilltrackalongthememoryuntila0memoryvalueisreached(oftencalledthenullterminator). C++stringscancontainembedded\0characters,knowtheirlengthwithoutcounting. #include #include #include usingnamespacestd; voidNullTerminatedString(stringstr){ intNUll_term=3; str[NUll_term]='\0';//specificcharacteriskeptasNULLinstring cout<and#include"filename"? 3712 WhatarethedifferencesbetweenapointervariableandareferencevariableinC++? 3257 HowdoIiterateoverthewordsofastring? 4528 HowdoIread/convertanInputStreamintoaStringinJava? 4678 HowdoImakethefirstletterofastringuppercaseinJavaScript? 5191 HowtoreplacealloccurrencesofastringinJavaScript 7415 HowtocheckwhetherastringcontainsasubstringinJavaScript? 3590 DoesPythonhaveastring'contains'substringmethod? 3717 Whyischar[]preferredoverStringforpasswords? HotNetworkQuestions Uglyshadowglitch Isthisconceptforverylowenergyspacetravelplausible? Howtallarethemushrooms? SciFiinvolvingportalstodistantworldsthatleavepeoplestrandedfarfromearth Upperboundforrandomcorrelation Hypothetically,canearlyhumansdomesticategiantantssimilartowolves?Maybeevenassistthemintheagriculturalrevolution? Whatdoes"CATsthreeandfour"mean? Whycan'tItakephotosinsideofstoresinPortugal? Whydoesthegovernmentnotintroduceanamendmenttotheconstitutiontoallowabortion? CatalinakeepsondownloadingunwantedMonterey-Installerwithoutanynotification Willmymeatloafcookifthesauceismixedintothemeat Firsttimeflyingwithcarryononly.CanIcarrydoubleedgedrazorbladeswithme? ConfusionwithDopplerEffectproblem WhyareRoevWadeandPlannedParenthoodvCaseyabbreviatedasRoeandCasey? Doesmycathatemenow RecordsgreaterthanepochtimestampusingonlyLIKEoperator Whatisthepurposeofindexingthemempoolbythesefivecriteria? HowcanIaddalayerofmeaningtoanevilcampaign? Whydoprogunandantiabortion(andviceversa)viewsgotogetherintheUSA? usingnamespacestdcausesboostpointercasttotriggerADLinc++17standard IsDaryl'sMailLegitThisTime? Whathappenswhenthesegmentplusoffsetoverflows20bits? WhywouldanyonebuyaPonyoveraMule? /var/loghasreached56.6GB.Howtocleanitandmakemorespace? morehotquestions Questionfeed SubscribetoRSS Questionfeed TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader. lang-cpp Yourprivacy Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy. Acceptallcookies Customizesettings  



請為這篇文章評分?