【问题标题】:Output position of Pointer in string C++字符串 C++ 中指针的输出位置
【发布时间】:2016-11-30 04:32:48
【问题描述】:

我现在下面的代码输出位置 0 的字母 H,但我想知道是否有一种方法不仅可以输出字母 H,还可以输出字母 H 的指针位置。

谢谢

#include "stdafx.h"
#include <iostream>
#include <string>

using namespace std;
int main(){
const char* letterPointer = "Harry"; 
cout << letterPointer[0] << endl
return 0;
}

【问题讨论】:

  • 试过(void*)&amp;letterPointer[0]?
  • 或者实际上只是letterPointer
  • 你问题的措辞有点不清楚。似乎您可能正在尝试从任意指针获取索引。例如,如果您在字符串中有一个指向 somewhere 的指针,并且想知道它的位置。 例如 char * p = strchr(letterPointer, 'r'); -- 在这种情况下你可以使用指针算法:int pos = p - letterPointer;

标签: c++ string pointers output


【解决方案1】:

为此,从char * 转换为void * 是一种常用技术,如下所示:

cout << static_cast<const void*>(&letterPointer[0]) << endl;

顺便说一句,在 C++ 中,string 不是指char *,而是std::string。 因此,您的代码中不需要此包含行。

#include <string> // You'd probably want to remove this line.

【讨论】:

  • 感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-28
  • 2018-11-05
  • 2011-09-17
  • 1970-01-01
相关资源
最近更新 更多