怎么用指针指向string类型
时间: 2023-09-18 17:10:42 浏览: 43
可以使用以下语法将指针指向 string 类型:
```
string str = "hello";
string* ptr = &str;
```
此时,`ptr` 将指向 `str` 的地址。可以通过解引用指针来访问字符串内容:
```
cout << *ptr << endl; // 输出 "hello"
```
还可以通过指针修改字符串内容:
```
*ptr = "world";
cout << str << endl; // 输出 "world"
```
相关问题
指针指向string
指针可以指向字符串,包括C风格的字符串和C++的std::string对象。下面是两个例子:
1. 指针指向C风格的字符串:
```cpp
char str[] = "hello world";
char *pstr = str;
```
2. 指针指向C++的std::string对象:
```cpp
#include <iostream>
#include <string>
int main() {
std::string str = "hello world";
const char *pstr = str.c_str();
std::cout << pstr << std::endl;
return 0;
}
```
在第一个例子中,我们定义了一个字符数组`str`,然后将指针`pstr`指向该数组的首地址。这样,`pstr`就指向了字符串"hello world"。
在第二个例子中,我们使用了C++的std::string类。首先,我们创建了一个std::string对象`str`并初始化为"hello world"。然后,我们使用`c_str()`成员函数获取字符串的C风格表示,并将其赋值给指针`pstr`。最后,我们通过`std::cout`输出了指针指向的字符串。
指针指向内容用string表示
在C++中,可以使用std::string来表示指针所指向的内容。std::string是C++标准库中的一个类,用于处理字符串。你可以将指针所指向的内容存储在std::string对象中,并使用该对象提供的成员函数来操作和访问字符串数据。
例如,你可以定义一个指向字符串的指针,并将其内容存储在std::string对象中:
```cpp
std::string str = "Hello, World!";
const char* ptr = str.c_str();
```
在这个例子中,我们将字符串"Hello, World!"存储在std::string对象str中,并通过调用str.c_str()函数获取一个指向字符串内容的const char*指针ptr。
请注意,使用std::string可以更方便地管理字符串内存,避免了手动分配和释放内存的麻烦。此外,std::string还提供了一系列函数来处理字符串,例如查找、替换、连接等操作。