Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/128.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何打印C字符串的内存地址?_C++_Arrays_Pointers_Memory_C Strings - Fatal编程技术网

C++ 如何打印C字符串的内存地址?

C++ 如何打印C字符串的内存地址?,c++,arrays,pointers,memory,c-strings,C++,Arrays,Pointers,Memory,C Strings,该函数打印动态数组的每个内存位置的地址。这条路对吗 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 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;
    }

}
intmain()
{
char str[]=“这是一个测试”;
打印地址(str,strlen(str));
}
模板
无效打印地址(类型*项,int n)
{

cout一种可能的方法是将C样式的
printf
%p
一起使用。因此,请包括,然后尝试以下示例:

 const char *sp = "abcde" + 2; // some computation giving a string address
 printf("sp=%p ('%s')\n", sp, sp);
或者,强制转换为
(void*)
,并使用通常的

std::cout << "sp at " << (void*)sp << std::endl;
std::cout运行以下命令:

#include <iostream>
#include <cstring>
using namespace std;

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 << "Index2 " << i << ": " << (void*) &item[i] << endl;
    }

}

int main()
{
    char str[] = "This is a test";
    printAddresses(str, strlen(str));
}
现在想想对于存储的字符,您希望看到什么序列?您希望每个字符都与前一个相邻(当然),并且每个字符都有一个存储单元。这应该告诉您:

(无效*)和项目[i]

这是正确的做法


还请注意,zmbq关于使用调试器查找的评论也很有意义



最后,我建议您阅读:

您获得不同内存地址的原因是您的代码错误

void printAddresses(type *item, int n)
item
是指向
printAddresses
模板函数的指针参数。因此,在以下表达式中:

    cout << "Index " << i << ": " << ((&item) + i)  << endl;
成为模板函数的参数地址,而不是数组地址

这就是为什么:

 (&item)+i
是错误的,并且完全没有意义。在这里,模板函数的参数地址并不是很有用

 (void*) &item[i]

是正确的答案。

正确的地址是您在打印
(void*)和项目[i]
时获得的地址


已经是指针;
项[i]也是指针
。如果您对打印此指针的值感兴趣,则需要将其强制转换为
void*
,然后调用
cast to
void*
来打印地址。请与调试器断开并查看。
cout在这种情况下,为什么
cout@user3577478这是一个极好的问题!这不起作用的原因是该运算符或者这更有意义。所以C字符串的处理方式和普通指针有点不同,但我会使用
std::adressof
来更好地表达意图。@xboi209感谢您的建议!您好,您能告诉我为什么
cout,因为
byte
很可能是
char
,所以
std::ostream
将尝试打印字符串,而不是指针地址。它看起来与将任何其他任意
char*
传递给
运算符没有什么不同
&item
 (&item)+i
 (void*) &item[i]
cout << "Index " << i << ": " << std::addressof(item[i]) << endl;