How to convert a string to a char array in C ? (c_str() Method)
c_str() provides read-only access to a null-terminated C-string; for writable arrays, manually copy data using vector or strncpy. Never cast away const or use the pointer after string destruction.

To convert a std::string to a char array in C , the c_str() method gives you a pointer to a null-terminated C-style string — but it does not give you a modifiable copy or a standalone array. It returns a const char*, meaning you can’t change the content through that pointer, and the memory is managed by the string object.
When you just need read-only access
If your goal is to pass the string to a C function (like printf, strlen, or open()) that expects a const char*, use c_str() directly:
std::string s = "hello";-
printf("%s", s.c_str());✅ works fine -
strcpy(buffer, s.c_str());✅ safe ifbufferis large enough
When you need a writable char array
c_str() won’t help here — you must copy the data manually. Use std::vector<char></char> or a raw array with strcpy / std::copy:
- Using
std::vector<char></char>:std::vector<char> arr(s.begin(), s.end());</char>arr.push_back('\0'); // add null terminator if needed - Using a C-style array:
char buffer[256];strncpy(buffer, s.c_str(), sizeof(buffer)-1);buffer[sizeof(buffer)-1] = '\0';
What not to do
Avoid treating c_str() as a mutable array:
-
char* p = const_cast<char>(s.c_str()); p[0] = 'H';</char>❌ undefined behavior -
char* arr = s.c_str();— then usingarraftersis modified or destroyed ❌ dangling pointer
Basically, c_str() is for safe, temporary, read-only access — not for creating independent, editable char arrays. If you need ownership or mutability, copy the data explicitly.
The above is the detailed content of How to convert a string to a char array in C ? (c_str() Method). For more information, please follow other related articles on the PHP Chinese website!
Hot AI Tools
Undress AI Tool
Undress images for free
AI Clothes Remover
Online AI tool for removing clothes from photos.
Undresser.AI Undress
AI-powered app for creating realistic nude photos
ArtGPT
AI image generator for creative art from text prompts.
Stock Market GPT
AI powered investment research for smarter decisions
Hot Article
Popular tool
Notepad++7.3.1
Easy-to-use and free code editor
SublimeText3 Chinese version
Chinese version, very easy to use
Zend Studio 13.0.1
Powerful PHP integrated development environment
Dreamweaver CS6
Visual web development tools
SublimeText3 Mac version
God-level code editing software (SublimeText3)
Hot Topics
20572
7
13671
4




