如何在C ++中找到字符的内存地址? [英] How Do I Find The Memory Address Of A Character In C++?
问题描述
我想找到一个角色的记忆地址,但我注意到了一些事情,我无法理解。
char name [] = {hello};
//查找内存地址这就是我所做的名字数组
cout<<名称[]的内存地址是:<<& name []< < endl;
//这个工作正常,现在我想在
名称数组中找到一个字符的内存地址
//说我想找到char h ||的内存地址char e
//所以这就是我找到的地址
cout<<名称的内存地址[0 ]是:<< &(name [0])<< endl;
//现在这里是问题,我得到错误的结果,我得到的是你好而不是获取内存地址
//我在网上找到了这个技巧,找到了名字[0]的内存地址
cout<<的内存地址name [0]是:<<< static_cast< void>(&(name [0])<< endl;
我不明白为什么&(name [0])dint工作的正常方法是什么,static_cast< void>(&(name [0])的含义是什么?它是做什么的?
请任何人用简单的语言解释一下。谢谢
I want to find the memory address of a character but i have noticed somethings and i am unable to understand it.
char name[] = {"hello"};
// to find the memory address of name array this is what i did
cout<<"The memory address of name[] is:"<<&name[]<<endl;
//this works fine and now i want to find the memory address of a character in the
name array
// say i want to find the memory address of char h || char e
//so this is what i did for finding the address
cout<<"The memory address of name[0] is:"<< &(name[0])<<endl;
//now here is the problem, i get wrong results, what i get is "hello" instead of getting the memory address
// i looked online and found this trick to find the memory address of name[0]
cout<<"the memory address of name[0] is:"<<static_cast<void>(&(name[0])<<endl;
I dont understand why the normal approach of &(name[0]) dint work and what is the meaning of static_cast<void>(&(name[0]) and what does it do?
Please can anyone explain me in simple terms. Thanks
推荐答案
你所拥有的是一个字符数组。name [0]
将返回第一个字符,& name [0]
将返回指向该字符的指针(内存地址)(char *
),如你所料。
发生了什么,是cout
正在解释char *
作为字符串和打印输出字符而不是地址。
使用static_cast
找到的技巧已经关闭,但它缺少一个关键部分 - 要转换的类型,目的是将char *
转换为void *
以便cout
不会将其视为字符串。
What you have is an array of chars.name[0]
will return the first char, and&name[0]
will return a pointer (the memory address) to that char (achar*
), as you expect.
What's happening though, is thatcout
is interpreting thatchar*
as a string and printing out the characters instead of the address.
The trick you found usingstatic_cast
is close, but it's missing a crucial part - the type to cast to, the aim is to cast thechar*
to avoid*
so thatcout
won't treat it as a string.
char name[] = "Hello";
cout<<"the memory address of name[0] is:"<<static_cast<void*>(&name[0])<<endl;
有关不同类型演员表的更多信息(因为 static_cast
不是唯一一个),请参阅 http://www.cplusplus.com/doc/tutorial/typecasting/ [ ^ ]
For more info on different types of casts (as static_cast
is not the only one) see http://www.cplusplus.com/doc/tutorial/typecasting/[^]
这篇关于如何在C ++中找到字符的内存地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!