Start New Discussion within our Software Development Community

Hey guys,

Was wondering if someone could assist me in elaborating the c_str() function...

I understand that it returns a pointer to an array that contains a null-terminated sequence of character but could someone further elaborate upon this, perhaps with a simple example.

Cheers,

Well, there are many types of strings. In standard C and C++ they are null terminated char arrays, meaning the null char needs to be the last char of the characters stored in the array. These strings can be manipulated by a number of standard functions. std:strings objects are instances of the string class found in the string class found in the string libraray of the Standad C++ library. String objects have a number of member variables, one of which is an array of char. However, the array of char in a std:string need not be null terminated. A number of functions need a null terminated char array as input. You can extract the char array of a std:string and use it as a null terminated char array by calling the c_str() method on a std:string object. For example, using appropriate headers in the program, the following should print Hello to the screen.

char string1[20];
string string2 = "Hello";
strcpy(string1, string2.c_str());
cout << string1;

This question has already been answered. Start a new discussion instead.