该函数打印动态数组每个内存位置的地址。这是正确的方法吗?
int main()
{
char str[] = "This is a test";
printAddresses(str, strlen(str));
}
template <class type>
void printAddresses(type *item, int n)
{
cout << "Printing Addresses..." << endl;
for (int i = 0; i < n; i++)
{
cout << "Index " << i << ": " << ((&item) + i) << endl;
}
}
我还听说我应该使用:
cout << "Index " << i << ": " << (void*) &item[i] << endl;
但这给了我不同的内存地址。我不确定哪个是正确的。
最佳答案
正确的地址是你打印时得到的(void*)&item[i]
.
item
已经是一个指针; &item[i]
也是.你有兴趣打印这个指针的值,你需要将它转换为 void*
打电话前 <<
在上面。
打印时 ((&item) + i)
你正在做一个额外的间接级别( &item
是一个指向指针的指针),所以你打印 item
的地址-指针,而不是什么的地址 item
指向。
注意:从 C++11 开始,您可以使用 std::addressof
函数代替运算符 &
为了更好的可读性和避免潜在的问题 T
为运算符 &
提供重载:
cout << "Index " << i << ": " << std::addressof(item[i]) << endl;
关于c++ - 如何打印出C-String的内存地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37911478/