如何将 C++ 字符串数组传递给 const char*
是的,可以使用字符串数组的第一个元素的地址来传递字符串数组给const char*。例如:
#include <iostream>
using namespace std;
int main() {
string arr[] = {'Hello', 'World'};
const char* str = arr[0].c_str();
cout << str << endl; // 输出 'Hello'
return 0;
}
在上面的示例中,我们使用c_str()函数获取字符串数组的第一个元素的地址,并将其分配给const char类型的变量。这使我们可以在程序中使用字符串数组的内容。但是需要注意的是,当字符串数组被修改或销毁时,const char指针将变得无效。
原文地址: https://www.cveoy.top/t/topic/mRic 著作权归作者所有。请勿转载和采集!