C-Style strings form a definitive part in majority of interview coding questions so I thought I should learn myself and add it to the page. I tried to ignore the C-Style string area but finally I am yielding to it ;) To start with, a C-Style string ('string' henceforth) is actually an array of characters terminated by null character ('\0') to mark the end of string.
For eg. "Interview" is actually an array of characters represented by:
[I] [n] [t] [e] [r] [v] [i] [e] [w] [\0]
The length of this string is therefore actually '10' so if we happen to copy this string in a character array we will need to allocate space for 10 characters. However, the library function 'strlen' returns the length of string excluding the terminating null character, thus in this case 'strlen' will return '9'.
A string is usually passed around and manipulated as a 'pointer to character (char*)' or an 'array of characters'; which are actually the same as name of array means a constant pointer pointing to the first element of that array.
Now let's write a function to print a simple string:
void PrintStr(char* str)
{
std::cout<<"\n String Passed: " <<>
}
int main()
{
char* chPtr = “Interview”;
PrintStr(chPtr);
}
This function correctly prints value of 'str'. But there is a problem in 'PrintStr' function, consider the 'main()' below:
int main()
{
char chArr[3] = {'A', 'B', 'C'};
PrintStr(chArr);
}
This compiles fine and executes well but have a look at the output:
So we just learnt a lesson that before using a C-Style string pointer it must be made sure that it is properly null terminated. A way to do this is to change the function signature to include length of string pointed to by the pointer so we may use only the memory said to be valid by length.
I agree. It's a basic concept one should expect to be asked in the interview directly or indirectly and must answer correctly. I would like to add one more thing to it. You are using char* in the first method and char[] in the second. They are similar in usage. Both are pointers to char array. But there is a slight difference between two and this is asked in some of the interviews. The char arrays are variable pointer to constant string. The char * are constant pointer to variable string. i.e you cannot change the elements in char array. You can assign new array to already declared char array. This is exactly the reverse for the char*.
ReplyDeleteTrue, thanks for pointing it out.
ReplyDelete