Size of a char array in C++

Asked By 40 points N/A Posted on -
qa-featured

The size of a char array that is declared to store a string should be one longer than the number of characters in the string. why?

SHARE
Best Answer by JamesAlexander
Answered By 0 points N/A #124861

Size of a char array in C++

qa-featured

Hi Santhosh

  • The size of array that is declared to store a string should always be one number higher than characters because  the array always starts from zero  and it subtracts  the no of characters subtract minus one 
  • Ex : Rajesh no of characters  = 6
  • The array should be declared as {7)

 

Best Answer
Best Answer
Answered By 0 points N/A #124862

Size of a char array in C++

qa-featured

When you take a character array, the elements are stored in consecutive memory locations. This is how a string is stored in memory.

S

T

R

I

N

G

  • So there should be a means by which compiler can identify when the string is terminated. So it is achieved by storing a null character at the end of the array. So whenever you declare a character array, there should be an additional bit meant for storing the null character.
  • This is the reason you should always allocate an extra 1 bit while declaring a character array.
  • So if you want to store a string which has 5 characters, you should declare a character array of size 6.

Login/Register to Answer

Related Questions