开发者

Memory address in dynamic allocation

开发者 https://www.devze.com 2023-04-11 01:44 出处:网络
#include <iostream> int main() { int anything[] = {5}; int *something = new int; *something = 5; std::cout << &anything<< \"==\" << &anything[0]<< \"==\" <&l
#include <iostream>

int main()
{
  int anything[] = {5};
  int *something = new int;
  *something = 5;

  std::cout << &anything  << "==" << &anything[0]  << "==" << anything  << std::endl;
  std::cout << &something << "!=" << &something[0] << "==" << something << std::endl;
}

Why is the memory address in &something different from &something[0] and something? Although it is a dynamic allocation, I don't understand why the memory address is different. I tried it with more than one value; it's the same thing. Here I use开发者_如何学编程d one value for both for simplicity.


&something is the memory address of the pointer itself (hey, it needs to store that value somewhere!), while &something[0] is the address of the actual memory that is storing your stuff.


something is a pointer. &something is the address of that pointer. &something[0] is the address of the first element pointed to by the pointer, which is completely different from the address of the pointer. something is the value of the pointer, which is also the address of the element that is pointed to.

I'm sure this topic has been covered many times before, I hope I did it justice.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号