You are here:

C++/confuse about string allocation

Advertisement


Question
we declare char *str="helloworld" how does c compiler allocate memory to this string of 10 chars as such we are not dynamically allocating.
how could we print cout<<str for which we did not allocate any memory,but char * is of 2 bytes.

Answer
Dear Shiva,
thankyou for your question, sorry for the delay.
Now lets review your question.

a) Your question, how does a pointer take two bytes.
Well the question is more hardware dependent, i guess
you have intermediate concepts about memory word which
take 2 Bytes and also the pointer allocation is compiler
dependent. Mostly C/C++ are 16 bit, it means 2bytes so
thats why they alloate two bytes to a Pointer as well.

b) Now as your question is related how this string will
have a memory allocation it will be like as

char *str = "helloworld";
Its allocation would be like

char *str = {"h", "e", "l", "l", "w","o","r","l","d", "\0" }

Now if i describe the following situation, basically a pointer stores the first byte of address, means first character memory location So in this case str is pointing towards address of letter h.

Now if you want to print it you can use the following statement if it is an array also.

cout << str ;

It will print out the character till the null character is not encountered where the string terminates.

I hope this helps. Don't be afraid if you have any other queries.

Regards
Professional

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Professional

Expertise

I can answer any question about functions,pointers,structures,object oriented programming basics of classes and data structures.My strong field is structured programming.

Experience

I have got 2 years experiece under C . I am able to answer about the structured concepts pointers to a little extent,OOP concepts. I have also experience in data Strucutres like Linked List, Stacks , Queues, Heaps, B Trees, Red Black Trees. I will try to satisfy with my knowledge. I am the Student of an expert here Martin, what i have learnt today, i just owe my every knowledge to him. He is the greatest.

©2016 About.com. All rights reserved.