Question about pointers
I understand the basics of how pointers work. I can get it to store the address of anything except a string. So my question is, how can I get it to store a string's address? If I try, it tells me "cannot convert 'std::string*' to 'int*' in initialization". Thanks.
Why do you try to store the address of a string (string*) in a pointer to an integer (int*)?
Oh, I though the pointer had to be an integer. That would be my problem (don't I feel dumb lol)...
But why does it have to be the same type as the variable? Since all pointers are the same since they only store an address, shouldn't they all be the same type?
Because the compiler knows (or WANTS to know) what the pointer is pointing at.
Originally Posted by TyPR124
It's possible to use a common-for-all-pointers pointer that is called void*. But this is not recommended if you can avoid it. It's usually used in C, because there's no templates there, but in C++, you should avoid them because the compiler will lose all type information about the type when you put it into a void* pointer.
Also, you can't derference a void* pointer since the compiler doesn't know its type.
But as matsp explained, it's because the compiler wants to know the type of object the pointer points to.
Yes, to clarify my and Elysia's potentially confusing statements:
1. a void * is compatible with "any pointer" in C. C++ is a bit more restrictive.
2. The compiler enforces the setting of pointers to "equivalent types" because it doesn't think it makes sense to take an int * and let it point to a string - because a string and an integer are not "compatible types".
3. The type of a pointer is only really there for two purposes:
- So that the compiler can access what the pointer points to - for example, a char * fetches [usually] a byte (8 bits) if you access the "pointed to" data, whilst an int * fetches a 32-bit value.
- For type checking - so you don't mistakenly set a pointer to point to something unsuitable. If you set a pointer to int to point to an array of char, you won't get a sensible integer out of that - so the compiler tells you when you "mix things up that aren't supposed to be mixed up".
You can, if you really think you know better than the compiler, use something called casts  to tell the compiler: "Look, I know that you don't think this makes sense, but I do really want to set this int pointer to the address of a string".
 The name cast is more of "casting a spell" to "magically convert this as is necessary" than "cast of plaster" that holds your broken leg in place.
Casting a spell is a pretty good analogy ("Remember the wizard Baruffio, who said f instead of s, and ended up with a buffalo on his chest."), but the word comes from casting iron or similar substances into a different form.
I thought it was typecasting, like when you typecast somebody. Or do I have them mixed up?
Well thanks for all the answers... I think I understand now.