Está en la página 1de 2

7/13/2016

cWhycanastringbeassignedtoachar*pointer,butnottoachar[]array?StackOverflow

signup

StackOverflowisacommunityof4.7
millionprogrammers,justlikeyou,
helpingeachother.

login

tour

help

JointheStackOverflowcommunityto:

Jointhemitonlytakesaminute:
Askprogramming
questions

Signup

Answerandhelp
yourpeers

Getrecognizedforyour
expertise

Whycanastringbeassignedtoachar*pointer,butnottoachar[]array?
Cansomeoneexplainwhythisworkswiththepointer:
char*str1;
str1="Hello1";
str1="newstring";
//butnotthis
charstr2[]="hello";
str2="four";
//orthis
charstr3[];
str3="hello";
str3="hello";
c string pointers initialization reusability
editedJul24'11at3:16

askedJul23'11at21:22

RobertHarvey
127k

28

nick

217

344

372

11

1 Thisquestioncoversthesameground,justwordeddifferently.I'mnotsureifthisisduplicateenoughto
close,butanswerstheredoapply.TimPost Jul24'11at3:17
2 @TimPost:TheallegedduplicatequestionanditsanswerareIMOunrelatedtothisquestionbecausethis
oneaskscompiletimethings,theotheroneasksruntimethings ArmenTsirunyanJul24'11at10:48

4Answers

Whyitworkswithpointers:
Whenyousay char*str1 inC,youareallocatingapointerinthememory.Whenyouwrite
str1="Hello"; ,youarecreatingastringliteralinmemoryandmakingthepointerpointtoit.
Whenyoucreateanotherstringliteral "newstring" andassignitto str1 ,allyouaredoingis
changingwherethepointerpoints.
Whyitdoesn'tworkwitharrays:
Whenyousay charstr2[]="Hello" ,youarecreatingastringliteralandputtingitinthearray
duringitsdefinition.Itisoktonotgiveasize,asthearraycalculatesitandappendsa '\0' toit.
Youcannotreassignanythingtothatarraywithoutresizingit.Thatiswhy str2="four" willnot
work.
Incaseof str3 ,itisthesamecase.Youhaven'tdefinedthesizeofthearrayinthedefinition,so
itcalculateditssizetobe0.Youcannotassignanythingnewwithoutresizingthearray.
editedDec12'14at21:16

Neftas
2,665

answeredJul23'11at21:34

tryurbest
3

17

33

645

17

Cheers,TryUrBest.MostCbooksI'velookedatmakeareallybigdealoutofstrings,pointersandarrays.In

thecaseofstr1(thepointer)isthatthewaytodoit?Stopworryingabout"amIdoingit100%correct"and
justmakepointerstostringsandusethemasIdidabove?Yousaid,thatthefirstmethodmovesthe
pointer,istheorig.datadestroyedthen,orisitaleak? nick Jul24'11at6:03
forgotthe@.thanks nick Jul24'11at7:08
@tryurbest:mayIaddfurtheraquestion?incaseusingchar*str="somestring",isthisstringconsideredto

beafixedsizestring.Iflateron,thispointerisprocessedtoaddmorestring.Willthatgenerateamemory
accessviolation?Thankyou!actually,I'vetesteditandseetheerror.ButI'mnotsureaboutthepart"fixed
sizestring"or"constantstring"overthereShawnLeNov29'14at3:08
Whathappenstotheoldstring"Hello".Doesthisbethereismemoryandcontributetomemoryleak?Or

thatisautomaticallyreleased?JonWheelock Oct11'15at2:05

http://stackoverflow.com/questions/6803387/whycanastringbeassignedtoacharpointerbutnottoachararray

1/2

7/13/2016

cWhycanastringbeassignedtoachar*pointer,butnottoachar[]array?StackOverflow

Anarrayandapointeraredifferentthings,that'swhy.Youcanassigntoapointer,butyoucan't
assigntoanarray.Aspecialexceptionismadeforinitializationofchararrayswithstringliterals.
chara[]="Hello";//initializeachararraywithstringliteral.Specialcase,OK
char*p="Hello";//initializaapointerwithanarray(whichgetsconvertedtopointer)
p="My";//assignpointertopointtoanothervalue.OK
a="My";//error,arrayscannotbeassignedto.Use`strcpy`

Stringliterals(suchas"Hello")havetype char[N] where N isnumberofcharacters(including


theterminating '\0' ).Anarraycanbeconvertedtoapointertoitsfirstelement,butarraysand
pointersarenotthesamething,whateversomebadbooksorteachersmaysay.
answeredJul23'11at21:24

ArmenTsirunyan
74.3k

31

205

336

2 Don'tforget const asanissuehere.Puppy Jul23'11at21:28


4 @DeadMG:AFAIKinCstringliteralsarenot constchar[N] .Theyare char[N] .That'swhywe(used
to)havetheimplicitconversionto char* ofstringliteralsinC++.AmIwrong?ArmenTsirunyanJul23
'11at21:30
@Armen:No,theyareofficiallynot constchar[N] ,butinreality,theyveryoftenare.Mostcompilersput
stringliteralsinreadonlymemory.Thatmeanstheusershouldgenerallynottrytodo *p='A'; .

RudyVelthuis Jul23'11at21:39
3 @Rudy:Regardlessofwherethecompilerkeepsastringliteral,doing *p='A' hasundefinedbehavior,
whichIMOisirrelevanttotheOP'squestion.Butthetypeofastringliteralis(unfortunately)just char[N]
inC.ArmenTsirunyanJul23'11at21:44
OKGuys,thanks.Armenmadeareallygoodpoint.Ihavereadthatpointersandarraysarebasicallythe

same. nick Jul24'11at5:50

Putsimply,becauseanarrayisnotafirstclassobjectinC/C++.Theonlywaytoassigntoan
arrayistousestr(n)cpyormemcpy.
Whileanarraycollapsesintoapointerwhenpassedtoafunction,itisnotpossibletoassignto
anarray,exceptatcompiletimeasinitialisation.
answeredJul23'11at21:30

Julian
1,618

10

13

Itissimplybecause,whenyouwritethiscode:
charstr2[]="hello";

oreven:
intarr[]={1,2,4,4,5};

itcreates str2 or arr asaconstantpointer.That'swhyyoucannotreassignanyothervalues


tothesepointerswhileinlatercaseyouarecreatinganormalpointerandyoucanassign
anythingtoit.
editedJan20'15at18:28

ChrisKrycho
1,585

10

answeredJul22'13at20:22

Sawan
22

57

http://stackoverflow.com/questions/6803387/whycanastringbeassignedtoacharpointerbutnottoachararray

2/2