Hi I am in the process of figuring out linked lists but one thing that is catching me out and I know it's probably fairly basic by how come when I try to create a new ship object and set it equal to getNewShip() I get an error?
#include <iostream>
usingnamespace std;
struct ship{
int x_coOrd;
int y_coOrd;
ship* nextShip;
};
ship* getNewShip(){
ship* p_ship = new ship;
p_ship->x_coOrd = 0;
p_ship->y_coOrd = 0;
p_ship->nextShip = p_ship;
return p_ship;
}
int main()
{
ship one = getNewShip(); // THIS DOES NOT WORK
}
but when i set ship one to be a pointer instead it compiles and works
I'm not sure whats so confusing. getNewShip returns a pointer and in the first snippet one is not a pointer. What should a fully constructed object do with a pointer to another object? What does a house do with the address to another house?
yeah it's pretty straight forward but what I don't understand is getNewShip returns a pointer
then ship* one a pointer itself stores a pointer,I thought a pointer can only store a memory address,so ship one would store a pointer that points to memory in the heap wouldn't you need a pointer that stores a pointer like **p?
@Kesk at line 22 a pointer stores the memory address of that current ship it's supposed to be set to NULL because I have not made a head pointer yet so yeah that should be null.
then ship* one a pointer itself stores a pointer,I thought a pointer can only store a memory address,so ship one would store a pointer that points to memory in the heap wouldn't you need a pointer that stores a pointer like **p?
A pointer to a pointer also stores only an address.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include <iostream>
int main()
{
int value = 73; // an int object.
int* ptr_a = &value; // pointer-to-an-int. Stores the address an int is stored at.
int* ptr_b = ptr_a; // pointer-to-an int. Stores the address an int is stored at.
int** ptr_c = &ptr_a; // pointer-to-a-pointer-to-int. Stores the address a pointer is stored at.
std::cout << "value: " << value << "\t\t&value: " << &value << '\n';
std::cout << "ptr_a: " << ptr_a << "\t\t&ptr_a: " << &ptr_a << '\n';
std::cout << "ptr_b: " << ptr_b << "\t\t&ptr_b: " << &ptr_b << '\n';
std::cout << "ptr_c: " << ptr_c << "\t\t&ptr_c: " << &ptr_c << '\n';
}
You can see that ptr_a and ptr_b store the same address, while residing at different ones. ptr_c stores the address of ptr_a while residing at yet another address in memory.
A pointer-to-pointer is only useful when you have a pointer hanging around in memory somewhere and you want to store its address (a situation that is not present in the OP.)