我不明白为什么链接列表的工作原理 [英] I don't understand why this is how linked lists work

查看:65
本文介绍了我不明白为什么链接列表的工作原理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我正在阅读的一本书中,链接列表显示如下:



 EnemySpaceShip * getNewEnemy() 
{
EnemySpaceShip * p_ship = new EnemySpaceShip;
p_ship-> x_coordinate = 0 ;
p_ship-> y_coordinate = 0 ;
p_ship-> weapon_power = 20 ;
p_ship-> p_next_enemy = p_enemies;
p_enemies = p_ship;
return p_ship;
}





我不明白的是,在线:



 p_ship-> p_next_enemy = p_enemies; 
p_enemies = p_ship;



这里当下一个敌人被分配时,它不应该采取下一个敌人的地址值,所以它应该是这样的:



 p_ship-> p_next_enemy =& p_enemies; 
p_enemies = p_ship;





我尝试过:



没什么........................................ ................

解决方案

快速回顾一下C ++中的指针:

< pre lang =c ++> EnemySpaceShip * ship; // 定义指针ship
ship; // 指针(值的地址)
* ship; //
& ship; // 指针的地址,返回的值是EnemySpaceShip **
// (指向指针的指针)



你的功能正在通过创建新船( p_ship )将新船插入现有船舶清单的前面,链接现有船舶清单( p_enemies )到新船,然后将船只列表指针设置为新船。



所以是的,它应该采取的地址它所做的敌舰列表。使用&将获取敌舰列表地址的地址。


查看如何声明p_enemies,并且它可能被声明为指针。



你不会说& p_enemies因为p_enemies已经是一个指针。您不需要获取指针的地址。实际上,它会使程序崩溃,因为当你试图取消引用指针的地址时,它会指向(可能)未分配的内存。


In a book I'm reading, linked lists are shown to be created like this:

EnemySpaceShip* getNewEnemy ()
{
  EnemySpaceShip* p_ship = new EnemySpaceShip;
  p_ship->x_coordinate = 0;
  p_ship->y_coordinate = 0;
  p_ship->weapon_power = 20;
  p_ship->p_next_enemy = p_enemies;
  p_enemies = p_ship;
  return p_ship;
}



What I don't understand is, on the lines:

p_ship->p_next_enemy = p_enemies;
p_enemies = p_ship;


Here when the next enemy is assigned, shouldn't it take the address value of the next enemy so it should look like this:

p_ship->p_next_enemy = &p_enemies;
p_enemies = p_ship;



What I have tried:

Nothing........................................................

解决方案

A quick recap on pointers in C++:

EnemySpaceShip* ship; //defining a pointer "ship"
ship; //the pointer (address of value)
*ship; //the value
&ship; //the address of the pointer, the value returned is EnemySpaceShip**
       //(pointer to a pointer)


What your function is doing is inserting the new ship at the front of the existing ship list by creating a new ship (p_ship), linking the existing ship list (p_enemies) to the new ship, then setting the ship list pointer to the new ship.

So yes it should take the address of the enemy ship list which it does. Using & would be taking the address of the address of the enemy ship list.


Look at how p_enemies is declared, and it's probably declared as a pointer.

You wouldn't say &p_enemies because p_enemies is already a pointer. You don't need to take the address of the pointer. In fact, it would crash the program, because when you attempt to dereference the address of the pointer, it would point (likely) to unallocated memory.


这篇关于我不明白为什么链接列表的工作原理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆